<?php
/**
 * rest_api.php
 *
 * Custom rest services
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    2.0
 * @link       http://opencart-api.com/product/opencart-restful-api-pro-v2-0/
 * @see        http://newapi2.opencart-api.com/demo/
 */

require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerFeedRestApi extends RestController {

    /*check database modification*/
    public function getchecksum() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){

            $this->load->model('catalog/product');

            $checksum = $this->model_catalog_product->getChecksum();

            $checksumArray = array();

            for ($i = 0; $i<count($checksum);$i++){
                $checksumArray[] = array('table' => $checksum[$i]['Table'], 'checksum' => $checksum[$i]['Checksum']);
            }

            $json = array('success' => true,'data' => $checksumArray);

            $this->sendResponse($json);
        }
    }

    /*
    * PRODUCT FUNCTIONS
    */
    public function products() {
        // var_dump($this->customer->getIsAll());

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get product details
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getProduct($this->request->get['id']);
            }else {
                //get products list

                /*check category id parameter*/
                if (isset($this->request->get['category']) && ctype_digit($this->request->get['category'])) {
                    $category_id = $this->request->get['category'];
                } else {
                    $category_id = 0;
                }

                $this->uselistProducts($category_id, $this->request);
            }
        }

    }

    public function uselistProducts($category_id, $request){
		
		if(!empty($request->get['search']) && !is_numeric($request->get['search']) && strtoupper(substr(PHP_OS, 0, 3)) != 'WIN'){ //通过搜索并且输入的不是纯数字以及服务器是非windows系统
			$this->sendResponse($this->searchProducts($request));
		}
		else{
			$this->sendResponse($this->listProducts($category_id, $request));
		}

    }

    /*
    * Get products list
    */
	/*
    * Get products list
    */
    public function listProducts($category_id, $request) {

        $json = array('success' => false);

        $this->load->model('catalog/product');

        $parameters = array(
            "limit" => 100,
            "start" => 1,
            'filter_category_id' => $category_id
        );

        /*check limit parameter*/
        if (isset($request->get['limit']) && ctype_digit($request->get['limit'])) {
            $parameters["limit"] = $request->get['limit'];
        }

        /*check page parameter*/
        if (isset($request->get['page']) && ctype_digit($request->get['page'])) {
            $parameters["start"] = $request->get['page'];
        }

        /*check search parameter*/
        if (isset($request->get['search']) && !empty($request->get['search'])) {
            $parameters["filter_name"] = $request->get['search'];
            $parameters["filter_tag"]  = $request->get['search'];
			$parameters["filter_sku"]  = $request->get['search'];
			
			//商品编码
			$parameters["filter_product_code"] = substr($request->get['search'],0,10);

        }

        /*check sort parameter*/
        if (isset($request->get['sort']) && !empty($request->get['sort'])) {
            $parameters["sort"] = $request->get['sort'];
        }
        
        /*check order parameter*/
        if (isset($request->get['order']) && !empty($request->get['order'])) {
            $parameters["order"] = $request->get['order'];
        }

        /*check filters parameter*/
        if (isset($request->get['filters']) && !empty($request->get['filters'])) {
            $parameters["filter_filter"] = $request->get['filters'];
        }

        /*check manufacturer parameter*/
        if (isset($request->get['manufacturer']) && !empty($request->get['manufacturer'])) {
            $parameters["filter_manufacturer_id"] = $request->get['manufacturer'];
        }

        /*check vendor parameter*/
        if (isset($request->get['vendor']) && !empty($request->get['vendor'])) {
            $parameters["filter_vendor_id"] = $request->get['vendor'];
        }

        /*check category id parameter*/
        if (isset($request->get['category']) && !empty($request->get['category'])) {
            $parameters["filter_category_id"] = $request->get['category'];
        }

        /*check subcategory id parameter*/
        if (isset($request->get['subcategory']) && !empty($request->get['subcategory'])) {
            $parameters["filter_sub_category"] = $request->get['subcategory'];
        }

        /*check tag parameter*/
        if (isset($request->get['tag']) && !empty($request->get['tag'])) {
            $parameters["filter_tag"] = $request->get['tag'];
        }

        /*check description parameter*/
        if (isset($request->get['filter_description']) && !empty($request->get['filter_description'])) {
            $parameters["filter_description"] = $request->get['filter_description'];
        }

        /*check simple list parameter*/
        $simpleList = false;
        if (isset($request->get['simple'])) {
            if(!empty($request->get['simple'])){
                $simpleList = true;
            }
        }

        /*check custom list parameter*/
        $customFields = false;
        if (isset($request->get['custom_fields'])) {
            if(!empty($request->get['custom_fields'])){
                $customFields = $request->get['custom_fields'];
            }
        }

        $parameters["start"] = ($parameters["start"] - 1) * $parameters["limit"];

        $products = $this->model_catalog_product->getProductsData($parameters, $this->customer);

        if (count($products) == 0 || empty($products)) {
            // $json['success'] = false;
            // $json['error']['warning'] = "没有找到产品";
            $json['success'] = true;
            $json['data'] = array();
        } else {
            $json['success'] = true;
            foreach ($products as $product) {
                $json['data'][] = $this->getProductInfo($product, $simpleList, $customFields);
            }
        }

		$count = count($products);

		$this->addSearchLog($parameters["filter_name"],$count); //添加搜索日志

        return $json;
    }

	//搜索商品
    public function searchProducts($request) {

        $json = array('success' => false);

        $this->load->model('catalog/product');

		$limit = 100;
		$start = 1;

        if (isset($request->get['limit']) && ctype_digit($request->get['limit'])) {
            $limit = $request->get['limit'];
        }

        if (isset($request->get['page']) && ctype_digit($request->get['page'])) {
            $start = $request->get['page'];
        }

		$start = ($start-1)*$limit;

		$keyword = trim($request->get['search']);

		/*全文搜索*/
		require_once(DIR_SYSTEM . 'xunsearch/php/lib/XS.php');

		$xs = new XS('bhz');

		$search = $xs->search;   //获取搜索对象
		
		$search->setFuzzy(true);	 //模糊搜索
		$search->setLimit($limit,$start);

		$products = $search->setAutoSynonyms()->setQuery($keyword)->search();  //搜索
		/*全文搜索*/
		
		/*$pdata = array();
		foreach($products as $v){			
			if($v->status == 1){
				$pdata[] = array(
					'name' => $v->name,
					'product_id' => $v->product_id
				);
			}
		}*/
		
		$count;
        if(count($products) == 0 || empty($products)){
            $json['success'] = true;
            $json['data'] = array();
			$count = count($products);
        }
		else{
            $json['success'] = true;
            foreach ($products as $data) {
				$temp = $this->getListInfo($data);
				if($temp){
					$json['data'][] = $temp;
				}
            }
			$count = count($json['data']);
			if($count == 0){
				$json['data'] = array();
			}
        }

		$this->addSearchLog($keyword,$count); //添加搜索日志

		$json['correct'] = $search->getCorrectedQuery($keyword); //纠错
		// $json['expand'] = $search->getExpandedQuery($keyword); //建议
		
		//排序条件
		if (isset($request->get['sort']) && !empty($request->get['sort'])) {
            $sort = $request->get['sort'];
        }
		else{
			$sort = ""; //默认
		}
		
		//倒序正序
		if (isset($request->get['order']) && !empty($request->get['order'])) {
            $order = $request->get['order'];
        }
		else{
			$order = ""; //默认
		}

		/*排序*/
		if($sort != ""){

			foreach($json['data'] as $key=>$v){
				$json['data'][$key][$sort] = $v[$sort];
			} 
			$temp = array();
			foreach ($json['data'] as $v) {
				$temp[] = $v[$sort];
			}

			if($order == "asc"){
				array_multisort($temp,SORT_ASC,$json['data']);
			}
			else if($order == "desc"){
				array_multisort($temp,SORT_DESC,$json['data']);
			}

		}
		/*排序*/

        return $json;
    }
	
    //获取列表商品必要信息
    public function getListInfo($data){

        $this->load->model('catalog/product');
        
        $retval = array();
        $id = $data->product_id;
        $result = $this->model_catalog_product->getListProduct($id,$this->customer);

        if($result){

            $product = $result[0];

            $this->load->model('tool/image');
            $this->load->model('catalog/category');


            /*product image*/
            if ($product['image'] != null && file_exists(DIR_IMAGE . $product['image'])) {
                $image = $this->model_tool_image->resize($product['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
            } else {
                $image = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
            }
            /*product image*/



            /*options选项*/
            foreach ($this->model_catalog_product->getProductOptions($product['product_id']) as $option) {
                if ($option['type'] == 'select' || $option['type'] == 'radio' || $option['type'] == 'checkbox' || $option['type'] == 'image') {
                    $option_value_data = array();
                    if(!empty($option['product_option_value'])){
                        foreach ($option['product_option_value'] as $option_value) {
                            //!$option_value['subtract'] || ($option_value['quantity'] > 0)
                            if (true) {
                                if ((($this->customer->isLogged() && $this->config->get('config_customer_price')) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
                                    $price = $this->currency->restFormat($this->tax->calculate($option_value['price'], $product['tax_class_id'], $this->config->get('config_tax')));
                                    $price_formated = $this->currency->format($this->tax->calculate($option_value['price'], $product['tax_class_id'], $this->config->get('config_tax')));
                                } else {
                                    $price = $this->currency->restFormat($this->tax->calculate(0, $product['tax_class_id'], $this->config->get('config_tax')));
                                    $price_formated = $this->currency->format($this->tax->calculate(0, $product['tax_class_id'], $this->config->get('config_tax')));
                                }

                                if (isset($option_value['image']) && file_exists(DIR_IMAGE . $option_value['image'])) {
                                    $option_image = $this->model_tool_image->resize($option_value['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                                } else {
                                    $option_image = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                                }

                                $option_value_data[] = array(
                                    'image'                 => $option_image,
                                    'price'                 => $price,
                                    'price_formated'        => $price_formated,
                                    'price_prefix'          => $option_value['price_prefix'],
                                    'product_option_value_id'=> $option_value['product_option_value_id'],
                                    'option_value_id'       => $option_value['option_value_id'],
                                    'name'                  => $option_value['name'],
                                    'quantity'  => !empty($option_value['quantity']) ? $option_value['quantity'] : 0
                                );
                            }
                        }
                    }
                    $options[] = array(
                        'name'              => $option['name'],
                        'type'              => $option['type'],
                        'option_value'      => $option_value_data,
                        'required'          => $option['required'],
                        'product_option_id' => $option['product_option_id'],
                        'option_id'         => $option['option_id'],
                        'flag' => true

                    );

                } elseif ($option['type'] == 'text' || $option['type'] == 'textarea' || $option['type'] == 'file' || $option['type'] == 'date' || $option['type'] == 'datetime' || $option['type'] == 'time') {
                    $option_value  = array();
                    if(!empty($option['product_option_value'])){
                        $option_value = $option['product_option_value'];
                    }
                    $options[] = array(
                        'name'              => $option['name'],
                        'type'              => $option['type'],
                        'option_value'      => $option_value,
                        'required'          => $option['required'],
                        'product_option_id' => $option['product_option_id'],
                        'option_id'         => $option['option_id'],
                        'flag' => true
                    );
                }
            }
            /*options选项*/
            
            /*原价*/
            $price = $this->currency->restFormat($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $price_formated = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            /*原价*/

                /*原价*/
            $sale_price = $this->currency->restFormat($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $sale_price_formated = $this->currency->format($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
            /*原价*/

            /*special特价*/
            if ((float)$product['special']) {
                $special = $this->currency->restFormat($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
                $special_formated = $this->currency->format($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
            }
            // if((empty($special))){
            //     $special = $sale_price;
            // }
            // if(!(($special_formated))){
            //     $special_formated = $sale_price_formated;
            // }
            /*special特价*/

            $show_cart = 1;
            if($product['is_single'] != 1){
                $show_cart = 0;
            }
            else if( $options[0]['option_value'][0]['quantity'] < $product['minimum']){
                //$show_cart = 2; //备货中
            }

            $days = (int)((time()-strtotime($product['date_added']))/(24*3600));
            if(($days < 60 || $product['newpro'] == 1) && $product['show_new'] == 1){
                $show_new = 1;
            }
            else{
                $show_new = 0;
            }
            // if ($product['clearance']||$product['lack_status']==3) {
                $clearqty = $this->model_catalog_product->getclearqty($product['product_id']);
            // }
            $retval = array(
                'id' => $product['product_id'],
                'name' => $data->name,
                'image' => $image,
                'price' => $price,
                'price_formated'    => $price_formated,
                'special' => $special,
                'special_formated'  => $special_formated,
                'minimum' => $product['minimum'] ? $product['minimum'] : 1,
                'options'    => $options,
                'quantity' => $product['quantity'],
                'show_new' => $show_new,
                'show_clearance' => $product['show_clearance'],//是否显示“折”
                'recommend' => $product['recommend'],
                'clearance' => $product['clearance'],
                'sku' => $product['sku'],
                'lack_status' => $product['lack_status'],
                'lack_reason' => $product['lack_reason'],
                'promotion' => $product['promotion'],
                'is_single' => $product['is_single'],
                'option_value_quantity' => $options[0]['option_value'][0]['quantity'],
                'show_cart' => $show_cart,
                'clearqty' => $clearqty ,

                'sort_order' => $product['sort_order']
            );

            return $retval;

        }

    }
	//添加搜索日志
	public function addSearchLog($search,$count){

		$this->addHotSearch($search); //添加旧热门词搜

		$this->load->model('catalog/xunsearch');

		$this->model_catalog_xunsearch->addSearchLog($search,$count);

	}
	

    public function addHotSearch($filter_name){
        $this->load->model('catalog/product');
        $addhot = $this->model_catalog_product->addHotSearch($filter_name);
    }

   public function homepagelistProducts() {
        $this->load->model('catalog/product');
        $simpleList = false;  
        $customFields = false;
        $parameters = array(
            "start" => 1,
            'filter_category_id' =>0
        );       
        $parameters["limit"] = 4;
        $parameters["sort"] = 'sort_order';
        $parameters["order"] = 'DESC';
        $parameters["start"] = ($parameters["start"] - 1) * $parameters["limit"];

        $products = $this->model_catalog_product->getProductsData($parameters, $this->customer);

        if (count($products) == 0 || empty($products)) {
            $json['success'] = false;
            $json['error']['warning'] = "没有找到产品";
        } else {
            $json['success'] = true;
            foreach ($products as $product) {
                $json['data'][] = $this->getProductInfo($product, $simpleList, $customFields);
            }
        }

        return $json;
    }












    /*
    * Get product details
    */
    public function getProduct($id) {

        $json = array('success' => true);

        $this->load->model('catalog/product');

        $products = $this->model_catalog_product->getProductsByIds(array($id), $this->customer);
        if(!empty($products)) {
            $json["data"] = $this->getProductInfo(reset($products));
        } else {
            $json['success']     = false;
            $json['error']['warning'] = '没有找到此产品';
        }

        $vendorsimpleinfo = $this->getVendorSimpleInfo($id);
        if($vendorsimpleinfo){
            $json['data']['vendor'] = $vendorsimpleinfo; 
        }else{
            $json['data']['vendor'] = null;
        }

        $json['data']['logcenter_ship'] = $this->getLogcentership();
        $json['data']['delivery_info'] = $json['data']['logcenter_ship']['text'];

        //增加是否在当前用户的wishlist中
        $this->load->model('account/wishlist');
        $is_in_wishlist = $this->model_account_wishlist->isProductInWishlist($id);
        $json['data']['is_in_wishlist'] = $is_in_wishlist;

		//查找组合商品列表
		if($json['data']['product_type']==2){

			$group_products = $this->model_catalog_product->getGroupProducts($json['data']['id']);
			foreach($group_products as &$value){		
				
				$value['show_cart'] = 1;
				$value['special'] = $this->model_catalog_product->getNowSpecial($value['id']);
                //如果特价不存在，取售价
                if ((int)$value['special']==0) {
                    $value['special'] = $value['sale_price'];
                }
				$value['options'] = $this->model_catalog_product->getProductOptions($value['id']);
				if(isset($value['image']) && file_exists(DIR_IMAGE . $value['image'])){
					$value['image'] = $this->model_tool_image->resize($value['image'], 78, 78);
				}
				else{
					$$value['image'] = $this->model_tool_image->resize('no_image.jpg', 78, 78);
				}

			}

			$json['data']['group_products'] = $group_products;

		}
        
        $this->sendResponse($json);
    }

    private function getVendorSimpleInfo($id){
        $this->load->model('catalog/vendor');
        $this->load->model('tool/image');
        $query = $this->model_catalog_vendor->getVendorByProductId($id);

        if (isset($query['vendor_image']) && file_exists(DIR_IMAGE . $query['vendor_image'])) {
            $image = $this->model_tool_image->resize($query['vendor_image'], 400, 200);
        } else {
            $image = $this->model_tool_image->resize('no_image.jpg', 400, 200);
        }

        $vendor  = array(
            'vendor_id'   => $query['vendor_id'], 
            'vendor_name' => $query['vendor_name'],
            'vendor_image'       => $image,
            );
        
        return $vendor;
    }

    private function getProductInfo($product, $simpleList=false, $customFields=false){

        $this->load->model('tool/image');
        $this->load->model('catalog/category');

        //product image
        if ($product['image'] != null && file_exists(DIR_IMAGE . $product['image'])) {
            $image = $this->model_tool_image->resize($product['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
        } else {
            $image = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
        }

        //special
        if ((float)$product['special']) {
            $special = $this->currency->restFormat($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
            $special_formated = $this->currency->format($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
        }

        //additional images
        $images = array();
        $reviews = array();
        $discounts = array();
        $options = array();
        $productCategories = array();

        if(!$simpleList){
            $additional_images = $this->model_catalog_product->getProductImages($product['product_id']);

            foreach ($additional_images as $additional_image) {
                if (isset($additional_image['image']) && file_exists(DIR_IMAGE . $additional_image['image'])) {
                    $images[] = $this->model_tool_image->resize($additional_image['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                } else {
                    $images[] = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                }
            }

            

            //discounts
            $data_discounts = $this->model_catalog_product->getProductDiscounts($product['product_id']);

            foreach ($data_discounts as $discount) {
                $discounts[] = array(
                    'quantity' => $discount['quantity'],
                    'price' => $this->currency->restFormat($this->tax->calculate($discount['price'], $product['tax_class_id'], $this->config->get('config_tax'))),
                    'price_formated' => $this->currency->format($this->tax->calculate($discount['price'], $product['tax_class_id'], $this->config->get('config_tax')))
                );
            }

            //options
            foreach ($this->model_catalog_product->getProductOptions($product['product_id']) as $option) {
                if ($option['type'] == 'select' || $option['type'] == 'radio' || $option['type'] == 'checkbox' || $option['type'] == 'image') {
                    $option_value_data = array();
                    if(!empty($option['product_option_value'])){
                        foreach ($option['product_option_value'] as $option_value) {
                            //!$option_value['subtract'] || ($option_value['quantity'] > 0)
                            if (true) {
                                if ((($this->customer->isLogged() && $this->config->get('config_customer_price')) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
                                    $price = $this->currency->restFormat($this->tax->calculate($option_value['price'], $product['tax_class_id'], $this->config->get('config_tax')));
                                    $price_formated = $this->currency->format($this->tax->calculate($option_value['price'], $product['tax_class_id'], $this->config->get('config_tax')));
                                } else {
                                    $price = $this->currency->restFormat($this->tax->calculate(0, $product['tax_class_id'], $this->config->get('config_tax')));
                                    $price_formated = $this->currency->format($this->tax->calculate(0, $product['tax_class_id'], $this->config->get('config_tax')));
                                }

                                if (isset($option_value['image']) && file_exists(DIR_IMAGE . $option_value['image'])) {
                                    $option_image = $this->model_tool_image->resize($option_value['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                                } else {
                                    $option_image = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                                }

                                $option_value_data[] = array(
                                    'image'					=> $option_image,
                                    'price'					=> $price,
                                    'price_formated'		=> $price_formated,
                                    'price_prefix'			=> $option_value['price_prefix'],
                                    'product_option_value_id'=> $option_value['product_option_value_id'],
                                    'option_value_id'		=> $option_value['option_value_id'],
									'product_code'       => $option_value['product_code'],
                                    'name'					=> $option_value['name'],
                                    'quantity'	=> !empty($option_value['quantity']) ? $option_value['quantity'] : 0
                                );
                            }
                        }
                    }
                    $options[] = array(
                        'name'				=> $option['name'],
                        'type'				=> $option['type'],
                        'option_value'		=> $option_value_data,
                        'required'			=> $option['required'],
                        'product_option_id' => $option['product_option_id'],
                        'option_id'			=> $option['option_id'],

                    );

                } elseif ($option['type'] == 'text' || $option['type'] == 'textarea' || $option['type'] == 'file' || $option['type'] == 'date' || $option['type'] == 'datetime' || $option['type'] == 'time') {
                    $option_value  = array();
                    if(!empty($option['product_option_value'])){
                        $option_value = $option['product_option_value'];
                    }
                    $options[] = array(
                        'name'				=> $option['name'],
                        'type'				=> $option['type'],
                        'option_value'		=> $option_value,
                        'required'			=> $option['required'],
                        'product_option_id' => $option['product_option_id'],
                        'option_id'			=> $option['option_id'],
                    );
                }
            }

            $product_category  = $this->model_catalog_product->getCategories($product['product_id']);

            foreach ($product_category as $prodcat) {
                $category_info = $this->model_catalog_category->getCategory($prodcat['category_id']);
                if ($category_info) {
                    $productCategories[] = array(
                        'name' => $category_info['name'],
                        'id' => $category_info['category_id']
                    );
                }
            }

            /*reviews*/
            $this->load->model('catalog/review');

            $reviews_total = $this->model_catalog_review->getTotalReviewsByProductId($product['product_id']);

            $reviewList = $this->model_catalog_review->getReviewsByProductId($product['product_id'], 0, 1000);


            $rating_total=0;
            $rating_best=0;
            $rating_mid=0;
            $rating_bad=0;
            $reviews_menu=array();
            foreach ($reviewList as $review) {
                $reviews['reviews'][] = array(
                    'author'     => $review['author'],
                    'text'       => nl2br($review['text']),
                    'rating'     => (int)$review['rating'],
                    'date_added' => date($this->language->get('datetime_format'), strtotime($review['date_added'])),
                    'avatar'     => $review['avatar'],
                    'is_anony'=> $review['is_anony'],
                );
                 $rating_total+=(int)$review['rating'];
                 switch ($review['rating']) {
                    case '1':
                         $rating_bad++;
                         break;
                    case '2':
                         $rating_mid++;
                         break;
                    case '3':
                         $rating_mid++;
                         break;
                    case '4':
                         $rating_best++;
                         break;
                    case '5':
                         $rating_best++;
                         break;
                     default:
                         # code...
                         break;
                 }
            
            }
            /*评论数学期望*/
            //$reviews['rating_total']=$rating_total;
            if($reviews_total==0){
            $review_total_rating ='0';  
            }else{
            $review_total_rating = round( $rating_total/$reviews_total*2)/2;  
            }
            $reviews_menu= array(
                'rating_best' => $rating_best, 
                'rating_mid' => $rating_mid, 
                'rating_bad' => $rating_bad, 
                'reviews_total' => $reviews_total,
                'review_total_rating' => $review_total_rating
                );
            $reviews['reviews_menu']=$reviews_menu;     
        }else{

            //增加option
            foreach ($this->model_catalog_product->getProductOptions($product['product_id']) as $option) {
                if ($option['type'] == 'select' || $option['type'] == 'radio' || $option['type'] == 'checkbox' || $option['type'] == 'image') {
                    $option_value_data = array();
                    if(!empty($option['product_option_value'])){
                        foreach ($option['product_option_value'] as $option_value) {
                            $option_value_data[] = array(
                                'product_option_value_id' => $option_value['product_option_value_id'],
								'quantity'	=> !empty($option_value['quantity']) ? $option_value['quantity'] : 0
                            );
                        }
                    }
                    $options[] = array(
                        'option_value' => $option_value_data,
                        'product_option_id' => $option['product_option_id'],
                        'flag' => true
                    );

                }elseif ($option['type'] == 'text' || $option['type'] == 'textarea' || $option['type'] == 'file' || $option['type'] == 'date' || $option['type'] == 'datetime' || $option['type'] == 'time') {
                    $options[]['flag'] = false;
                }
            }

        }
        
        
        
        //未审核用户不能看到批发价
        $price = $this->currency->restFormat($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
        $price_formated = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
        $sale_price_formated = $this->currency->format($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
        if($this->customer->getNeedReview()){
            $special = $product['price'];
            $special_formated = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $price = null;
            $price_formated = null;
        }
        if((empty($special))){
            $special = $price;
        }
        if(!(($special_formated))){
            $special_formated = $sale_price_formated;
        }

		$show_cart = 1;
		if($product['is_single'] != 1){
			$show_cart = 0;
		}
		else if( $options[0]['option_value'][0]['quantity'] < $product['minimum']){
			//$show_cart = 2; //备货中
		}

		$days = (int)((time()-strtotime($product['date_added']))/(24*3600));
		if(($days < 60 || $product['newpro'] == 1) && $product['show_new'] == 1){
			$show_new = 1;
		}
		else{
			$show_new = 0;
		}

        $retval = array(
            'id'				=> $product['product_id'],
            'seo_h1'			=> (!empty($product['seo_h1']) ? $product['seo_h1'] : "") ,
            'name'				=> $product['name'],
            'manufacturer'		=> $product['manufacturer'],
            'sku'				=> (!empty($product['sku']) ? $product['sku'] : "") ,
			'product_code'             =>$product['product_code'],
            'model'				=> $product['model'],
            'image'				=> $image,
            'images'			=> $images,
            'price'				=> $price,
            'price_formated'    => $price_formated,
            'rating'			=> (int)$product['rating'],
            'description'		=> html_entity_decode($product['description'], ENT_QUOTES, 'UTF-8'),
            'attribute_groups'	=> empty($simpleList) ? $this->model_catalog_product->getProductAttributes($product['product_id']) : array(),
            'special'			=> $special,
            'special_formated'  => $special_formated,
	        'special_start_date'=> (!empty($product['special_start_date']) ? $product['special_start_date'] : "") ,
	        'special_end_date'	=> (!empty($product['special_end_date']) ? $product['special_end_date'] : "") ,
            'discounts'			=> $discounts,
            'options'			=> $options,
            'minimum'			=> $product['minimum'] ? $product['minimum'] : 1,
            'addnum'            => $product['addnum'] ? $product['addnum'] : 1,
	        'meta_title'     => $product['meta_title'],
	        'meta_description'     => $product['meta_description'],
	        'meta_keyword'     => $product['meta_keyword'],
            'tag'              => $product['tag'],
            'upc'              => $product['upc'],
            'ean'              => $product['ean'],
            'jan'              => $product['jan'],
            'isbn'             => $product['isbn'],
            'mpn'              => $product['mpn'],
            'location'         => $product['location'],
            'stock_status'     => $product['stock_status'],
            'manufacturer_id'  => $product['manufacturer_id'],
            'tax_class_id'     => $product['tax_class_id'],
            'date_available'   => $product['date_available'],
            'weight'           => $product['weight'],
            'weight_class_id'  => $product['weight_class_id'],
            'length'           => $product['length'],
            'width'            => $product['width'],
            'height'           => $product['height'],
            'length_class_id'  => $product['length_class_id'],
            'subtract'         => $product['subtract'],
            'sort_order'       => $product['sort_order'],
            'status'           => $product['status'],
            'date_added'       => $product['date_added'],
            'date_modified'    => $product['date_modified'],
            'viewed'           => $product['viewed'],
            'weight_class'     => $product['weight_class'],
            'length_class'     => $product['length_class'],
            'reward'			=> $product['reward'],
            'points'			=> $product['points'],
            'packing_no'            => $product['packing_no'],
			'product_type'             =>$product['product_type'],
			'show_new' => $show_new,
            'show_clearance' => $product['show_clearance'],//是否显示“折”
			'recommend' => $product['recommend'],
            'clearance' => $product['clearance'],
            'lack_status' => $product['lack_status'],
			'lack_reason' => $product['lack_reason'],
			'promotion' => $product['promotion'],
			'is_single'             =>$product['is_single'],
            'category'			=> $productCategories,
            'quantity'			=> !empty($product['quantity']) ? $product['quantity'] : 0,
	        'reviews' => $reviews,
            'related'=>$this->getRelatedjson($product['product_id']),
			'option_value_quantity' => $options[0]['option_value'][0]['quantity'],
            'show_cart' => $show_cart ,  
			'clearqty' => $product['clearqty']	
        );
        if(!empty($customFields)) {
            $fields = explode(',', $customFields);
            $modRetval = array();
            if(is_array($fields)) {
                foreach ($fields as $field) {
                    $trimmed = trim($field);
                    if (isset($retval[$trimmed])) {
                        $modRetval[$trimmed] = $retval[$trimmed];
                    }
                }

                return $modRetval;
            }
        }

        return $retval;
    }


    public function search() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);
            $this->searchService($this->request, $requestjson);
        }
    }

    /*
   * Search products
   */
    public function searchService($request, $requestjson) {

        $json = array('success' => false);

        $this->load->model('catalog/product');

        $parameters = array(
            "limit" => 100,
            "start" => 1
        );

        /*check limit parameter*/
        if (isset($request->get['limit']) && ctype_digit($request->get['limit'])) {
            $parameters["limit"] = $request->get['limit'];
        }

        /*check page parameter*/
        if (isset($request->get['page']) && ctype_digit($request->get['page'])) {
            $parameters["start"] = $request->get['page'];
        }

        $parameters["start"] = ($parameters["start"] - 1) * $parameters["limit"];

        $products = $this->model_catalog_product->search($parameters, $requestjson, $this->customer);

        if (count($products) == 0 || empty($products)) {
            $json['success'] = false;
            $json['error']['warning']= "没有找到此产品";
        } else {
            $json['success'] = true;
            foreach ($products as $product) {
                $json['data'][] = $this->getProductInfo($product);
            }
        }

        $this->sendResponse($json);
    }

    public function hotSearch() {

        $this->checkPlugin();
        $json = array('success' => false);
        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            $cache = new Cache('file', 86400);
            $hot_search = $cache->get('hot_search');
            if(isset($this->request->get['limit'])){
                $filter_limit=$this->request->get['limit'];
            }else{
                $filter_limit=4;
            }
            if(!$hot_search) {
                $hot_search=$this->getHotSearch($filter_limit);           
                $cache->set('hot_search', $hot_search);
            }
            $json['success'] = true;
            $json['data']=$hot_search;  
            $this->sendResponse($json);
        }
    }
    public function getHotSearch($filter_limit){

        $this->load->model('catalog/product');
        return $this->model_catalog_product->getHotSearch($filter_limit);
    }
    /*
    * CATEGORY FUNCTIONS
    */
    public function categories() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get category details
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getCategory($this->request->get['id']);
            }else {
                //get category list

                /*check parent parameter*/
                if (isset($this->request->get['parent'])) {
                    $parent = $this->request->get['parent'];
                } else {
                    $parent = 0;
                }

                /*check level parameter*/
                if (isset($this->request->get['level'])) {
                    $level = $this->request->get['level'];
                } else {
                    $level = 1;
                }

                $this->listCategories($parent, $level);
            }
        }
    }

    /*
    * PRODUCT SPECIFIC INFOS
    */
    public function productclasses() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            $json = array('success' => true);

            $this->load->model('catalog/product');

            $json['data']['stock_statuses'] = $this->model_catalog_product->getStockStatuses();
            $json['data']['length_classes'] = $this->model_catalog_product->getLengthClasses();
            $json['data']['weight_classes'] = $this->model_catalog_product->getWeightClasses();
            $stores_result = $this->model_catalog_product->getStores();

            $stores = array();

            foreach ($stores_result as $result) {
                $stores[] = array(
                    'store_id'	=> $result['store_id'],
                    'name'      => $result['name']
                );
            }

            $default_store[] = array(
                'store_id'	=> 0,
                'name'      => $this->config->get('config_name')
            );

            $json['data']['stores'] = array_merge($default_store, $stores);

            $json['data']['recurrings'] = $this->model_catalog_product->getRecurrings();

            $this->load->model('localisation/currency');

            $json['data']['currencies'] = array();

            $results = $this->model_localisation_currency->getCurrencies();

            foreach ($results as $result) {
                if ($result['status']) {
                    $json['data']['currencies'][] = array(
                        'title'        => $result['title'],
                        'code'         => $result['code'],
                        'symbol_left'  => $result['symbol_left'],
                        'symbol_right' => $result['symbol_right']
                    );
                }
            }

            $this->load->model('localisation/return_reason');
            $json['return_reasons'] = $this->model_localisation_return_reason->getReturnReasons();

		    $this->sendResponse($json);

        } else{
	      $this->response->setOutput(json_encode(array('success' => false)));
        }
    }

    /*
    * Get categories list
    */
    public function listCategories($parent,$level) {

        $json['success']	= true;

        $this->load->model('catalog/category');

        $data = $this->loadCatTree($parent, $level);

        if(count($data) == 0){
            $json['success'] 	= false;
            $json['error'] ['warning']		= "没有找到此分类";
        }else {
            $json['data'] = $data;
        }

        $this->sendResponse($json);
    }

    /*
    * Get category details
    */
    public function getCategory($id) {
        
        $json = array('success' => true);

        $this->load->model('catalog/category');
        $this->load->model('tool/image');

        if (ctype_digit($id)) {
            $category_id = $id;
        } else {
            $category_id = 0;
        }

        $category = $this->model_catalog_category->getCategory($category_id);

        if(isset($category['category_id'])){

            $json['success']	= true;

            if (isset($category['image']) && file_exists(DIR_IMAGE . $category['image'])) {
                $image = $this->model_tool_image->resize($category['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
            } else {
                $image = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
            }

            $json['data']	= array(
                'id'			=> $category['category_id'],
                'name'			=> $category['name'],
                'description'	=> $category['description'],
                'image'         => $image,
                'filters'         => $this->getCategoryFilters($category_id)
            );
        }else {
            $json['success']     = false;
            $json['error']['warning']     = "这个分类不存在";

        }

        return $this->sendResponse($json);
    }

    public function loadCatTree($parent = 0, $level = 1) {

        $this->load->model('catalog/category');
        $this->load->model('tool/image');

        $result = array();

        $categories = $this->model_catalog_category->getCategories($parent);
		
        if ($categories && $level > 0) {
            $level--;

            foreach ($categories as $category) {
                if($parent==0) {
                    $width = 200;
                    $height = 200;
                } else {
                    $width = 90;
                    $height = 90;
                    // $width = $this->config->get('config_rest_api_image_width');
                    // $height = $this->config->get('config_rest_api_image_height');
                }

                if (isset($category['image']) && file_exists(DIR_IMAGE . $category['image'])) {
                    $image = $this->model_tool_image->resize($category['image'], $width, $height);
                } else {
                    $image = $this->model_tool_image->resize('no_image.jpg', $width, $height);
                }

				$next_cat = $this->loadCatTree($category['category_id'], $level);
				
				//组合商品超市和锅具特例二级分类
				if($category['category_id'] == 255 || $category['category_id'] == 752 || $category['category_id'] == 87){
					$all_level = 2;
				}
				else{
					$all_level = 3;
				}

                $result[] = array(
                    'category_id'   => $category['category_id'],
                    'parent_id'     => $category['parent_id'],
                    'name'          => $category['name'],
                    'sort_order'          => $category['sort_order'],
					'class_sort'          => $category['class_sort'],
                    'image'         => $image,
                    'filters'       => $this->getCategoryFilters($category['category_id']),
                    'categories'    => $next_cat,
					'all_level' => $all_level
                );
            }

            return $result;
        }
    }

    public function getToplevelCatsForHomepage() {
        $this->load->model('catalog/category');
        $this->load->model('tool/image');
        $result = array();
        $categories = $this->model_catalog_category->getCategories(0);
        $idx = 0;
        foreach ($categories as $category) {
            $idx++;
            if ($idx > 7) {
                break;
            }
            $width = ($idx == 1 || $idx == 7)?260*2:128*2;
            $height = 126*2;
            if (isset($category['home_image']) && file_exists(DIR_IMAGE . $category['home_image'])) {
                $image = $this->model_tool_image->resize($category['home_image'], $width, $height);
            } else {
                $image = $this->model_tool_image->resize('no_image.jpg', $width, $height);
            }
            $result[] = array(
                'category_id'   => $category['category_id'],
                'parent_id'     => $category['parent_id'],
                'name'          => $category['name'],
                'sort_order'          => $category['sort_order'],
				'class_sort'          => $category['class_sort'],
                'image'         => $image,
                'filters'       => $this->getCategoryFilters($category['category_id']),
                'categories'    => $this->loadCatTree($category['category_id'], 1)
            );
        }
        return $result;
    }


    /*
    * MANUFACTURER FUNCTIONS
    */
    public function manufacturers() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get manufacturer details
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getManufacturer($this->request->get['id']);
            }else {
                //get manufacturers list
                $this->listManufacturers();
            }
        }
    }

    /*
    * Get manufacturers list
    */
    public function listManufacturers() {

        $this->load->model('catalog/manufacturer');
        $this->load->model('tool/image');
        $json = array('success' => true);

        $data['start'] = 0;
        $data['limit'] = 1000;

        $results = $this->model_catalog_manufacturer->getManufacturers($data);

        $manufacturers = array();

        foreach ($results as $manufacturer) {
            $manufacturers[] = $this->getManufacturerInfo($manufacturer);
        }

        if(empty($manufacturers)){
            $json['success'] 	= false;
            $json['error']['warning'] 	= "没有找到此供应商";
        }else {
            $json['data'] 	= $manufacturers;
        }

        return $this->sendResponse($json);
    }



     public function homepagelistVendors($data) {

        $this->load->model('catalog/vendor');
        $this->load->model('tool/image');
        
        $results = $this->model_catalog_vendor->getVendors($data, true);
        $vendors = array();
        $idx = 0;
        foreach ($results as $vendor) {
            $vendor_tmp = $this->getVendorInfo($vendor);
            $idx++;
            switch ($idx) {
                case 1:
                    $width = 145*2;
                    $height = 200*2;
                    break;
                case 2:
                    $width = 224*2;
                    $height = 100*2;
                    break;
                default:
                    $width = 112*2;
                    $height = 100*2;
                    break;
            }
            if (isset($vendor['vendor_image']) && file_exists(DIR_IMAGE . $vendor['vendor_image'])) {
                $image = $this->model_tool_image->resize($vendor['vendor_image'], $width, $height);
            } else {
                $image = $this->model_tool_image->resize('no_image.jpg', $width, $height);
            }
            $vendor_tmp['image'] = $image;
            $vendor_tmp['link'] = 'feed/rest_api/vendors&id='.$vendor['vendor_id'];
            $vendors[] = $vendor_tmp;
        }

        if(empty($vendors)){
            $json['success']    = false;
            $json['error']['warning']   = "没有找到此供应商";
        }else {
            $json['data']   = $vendors;
        }
        return $json;
    }


   

    /*
    * Get manufacturer details
    */
    public function getManufacturer($id) {

        $json = array('success' => true);

        $this->load->model('catalog/manufacturer');
        $this->load->model('tool/image');

        if (ctype_digit($id)) {
            $manufacturer = $this->model_catalog_manufacturer->getManufacturer($id);
            if($manufacturer){
                $json['data'] = $this->getManufacturerInfo($manufacturer);
            } else {
                $json['success']     = false;
                $json['error']['warning']   = "这个商家不存在";
            }
        } else {
            $json['success'] 	= false;
        }

        $this->sendResponse($json);
    }

    private function getManufacturerInfo($manufacturer) {
        if (isset($manufacturer['image']) && file_exists(DIR_IMAGE . $manufacturer['image'])) {
            $image = $this->model_tool_image->resize($manufacturer['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
        } else {
            $image = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
        }
        return array(
            'manufacturer_id'=> $manufacturer['manufacturer_id'],
            'name'			=> $manufacturer['name'],
            'image'			=> $image,
            'sort_order'	=> $manufacturer['sort_order']
        );
    }



    /*
    * Vendor FUNCTIONS
    */
    public function vendors() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get Vendor details
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getVendor($this->request->get['id']);
            }else {
                //get Vendors list
                $this->listVendors();
            }
        }
    }
 
    /*
    * Get Vendors list
    */
    public function listVendors() {

        $this->load->model('catalog/vendor');
        $this->load->model('tool/image');
        $json = array('success' => true);

        $data['start'] = 0;
        $data['limit'] = 1000;
        $data['sort'] = 'sort_order';
        $data['order'] = 'DESC';

        $results = $this->model_catalog_vendor->getVendors($data);
        $Vendors = array();


        foreach ($results as $Vendor) {
            $Vendors[] = $this->getVendorInfo($Vendor);
        }

        if(empty($Vendors)){
            $json['success']    = false;
            $json['error']['warning']   = "没有找到此品牌";
        }else {
            $json['data']   = $Vendors;
        }

        return $this->sendResponse($json);
    }

    /*
    * Get Vendor details
    */
    public function getVendor($id) {

        $json = array('success' => true);

        $this->load->model('catalog/vendor');
        $this->load->model('tool/image');

        if (ctype_digit($id)) {
            $Vendor = $this->model_catalog_vendor->getVendor($id);
            if($this->model_catalog_vendor->getVendorList($id)){
                $Vendor['vendor_product'] = $this->model_catalog_vendor->getVendorList($id);
            }

            if($this->model_catalog_vendor->getTotalNewProductByVendorId($id)){
                $Vendor['total_new'] = $this->model_catalog_vendor->getTotalNewProductByVendorId($id);
            }

            if($Vendor){
                $json['data'] = $this->getVendorInfo($Vendor);
            } else {
                $json['success']     = false;
                $json['error']['warning']   = "这个品牌不存在";
            }
        } else {
            $json['success']    = false;
        }

        $this->sendResponse($json);
    }

    private function getVendorInfo($Vendor) {
        $this->load->model('tool/image');
        $this->load->model('catalog/vendor');
        $image=$this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
        if (isset($Vendor['vendor_image']) && file_exists(DIR_IMAGE . $Vendor['vendor_image']) && !empty($Vendor['vendor_image'])) {
            $image = $this->model_tool_image->resize($Vendor['vendor_image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
        } else {
            $image = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
        }
        $data= array(
            'vendor_id'=> $Vendor['vendor_id'],
            'name'          => $Vendor['vendor_name'],
            'image'         => $image,      
        );
        if(isset($Vendor['vendor_description'])){
            $data['vendor_description'] = $Vendor['vendor_description'];
        }else{
             $data['vendor_description'] = null;
        }

        if(isset($Vendor['sort_order'])){
            $data['sort_order'] = $Vendor['sort_order'];
        }else{
             $data['sort_order'] = null;
        }

        if(isset($Vendor['vendor_product'])){
            $data['vendor_product'] = $Vendor['vendor_product'];
        }

        if(isset($Vendor['total_new'])){
            $data['total_new'] = $Vendor['total_new'];
        }

        if(isset($Vendor['tax_id'])){
            $data['tax_id'] = $Vendor['tax_id'];
        }
        
        $data['is_in_wishlist'] = $this->model_catalog_vendor->checkIs_in_wishlist($Vendor['vendor_id']);

        if(isset($Vendor['products_image'])){  
            $products_image_private=$Vendor['products_image'];
            
            $Vendor['products_image']['0']=$this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
            $Vendor['products_image']['1']=$this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
            $Vendor['products_image']['2']=$this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));    
           foreach ($products_image_private as $key => $value) {

                 if (($value) && file_exists(DIR_IMAGE . $value)) {
                    $Vendor['products_image'][$key] = $this->model_tool_image->resize($value, $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                } else {
                    $Vendor['products_image'][$key] = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                }
           }
            $data['products_image'] = $Vendor['products_image'];
        }
        
        
        return $data;
    }

    

    /*
    * ORDER FUNCTIONS
    */
    public function orders() {

        $this->checkPlugin();

        $this->returnDeprecated();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get order details
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getOrder($this->request->get['id']);
            }else {
                //get orders list
                $this->listOrders();
            }
        }
    }

    /*
    * List orders
    */
    public function listOrders() {

        $json = array('success' => true);


        $this->load->model('account/order');

        /*check offset parameter*/
        if (isset($this->request->get['offset']) && $this->request->get['offset'] != "" && ctype_digit($this->request->get['offset'])) {
            $offset = $this->request->get['offset'];
        } else {
            $offset 	= 0;
        }

        /*check limit parameter*/
        if (isset($this->request->get['limit']) && $this->request->get['limit'] != "" && ctype_digit($this->request->get['limit'])) {
            $limit = $this->request->get['limit'];
        } else {
            $limit 	= 10000;
        }

        /*get all orders of user*/
        $results = $this->model_account_order->getAllOrders($offset, $limit);

        $orders = array();

        if(count($results)){
            foreach ($results as $result) {

                $product_total = $this->model_account_order->getTotalOrderProductsByOrderId($result['order_id']);
                $voucher_total = $this->model_account_order->getTotalOrderVouchersByOrderId($result['order_id']);

                $orders[] = array(
                    'order_id'		=> $result['order_id'],
                    'name'			=> $result['firstname'] . ' ' . $result['lastname'],
                    'status'		=> $result['status'],
                    'date_added'	=> $result['date_added'],
                    'products'		=> ($product_total + $voucher_total),
                    'total'			=> $result['total'],
                    'currency_code'	=> $result['currency_code'],
                    'currency_value'=> $result['currency_value'],
                );
            }

            if(count($orders) == 0){
                $json['success'] 	= false;
                $json['error'] 		= "No orders found";
            }else {
                $json['data'] 	= $orders;
            }

        }else {
            $json['error'] 		= "No orders found";
            $json['success'] 	= false;
        }

        $this->sendResponse($json);
    }

    /*
    * List orders whith details
    */
    public function listorderswithdetails() {

        $this->checkPlugin();

        $this->returnDeprecated();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){

            $json = array('success' => true);


            $this->load->model('account/order');

            /*check limit parameter*/
            if (isset($this->request->get['limit']) && $this->request->get['limit'] != "" && ctype_digit($this->request->get['limit'])) {
                $limit = $this->request->get['limit'];
            } else {
                $limit 	= 100000;
            }

            if (isset($this->request->get['filter_date_added_from'])) {
                $date_added_from = date('Y-m-d H:i:s',strtotime($this->request->get['filter_date_added_from']));
                if($this->validateDate($date_added_from)) {
                    $filter_date_added_from = $date_added_from;
                }
            } else {
                $filter_date_added_from = null;
            }

            if (isset($this->request->get['filter_date_added_on'])) {
                $date_added_on = date('Y-m-d',strtotime($this->request->get['filter_date_added_on']));
                if($this->validateDate($date_added_on, 'Y-m-d')) {
                    $filter_date_added_on = $date_added_on;
                }
            } else {
                $filter_date_added_on = null;
            }


            if (isset($this->request->get['filter_date_added_to'])) {
                $date_added_to = date('Y-m-d H:i:s',strtotime($this->request->get['filter_date_added_to']));
                if($this->validateDate($date_added_to)) {
                    $filter_date_added_to = $date_added_to;
                }
            } else {
                $filter_date_added_to = null;
            }

            if (isset($this->request->get['filter_date_modified_on'])) {
                $date_modified_on = date('Y-m-d',strtotime($this->request->get['filter_date_modified_on']));
                if($this->validateDate($date_modified_on, 'Y-m-d')) {
                    $filter_date_modified_on = $date_modified_on;
                }
            } else {
                $filter_date_modified_on = null;
            }

            if (isset($this->request->get['filter_date_modified_from'])) {
                $date_modified_from = date('Y-m-d H:i:s',strtotime($this->request->get['filter_date_modified_from']));
                if($this->validateDate($date_modified_from)) {
                    $filter_date_modified_from = $date_modified_from;
                }
            } else {
                $filter_date_modified_from = null;
            }

            if (isset($this->request->get['filter_date_modified_to'])) {
                $date_modified_to = date('Y-m-d H:i:s',strtotime($this->request->get['filter_date_modified_to']));
                if($this->validateDate($date_modified_to)) {
                    $filter_date_modified_to = $date_modified_to;
                }
            } else {
                $filter_date_modified_to = null;
            }

            if (isset($this->request->get['page'])) {
                $page = $this->request->get['page'];
            } else {
                $page = 1;
            }

            if (isset($this->request->get['filter_order_status_id'])) {
                $filter_order_status_id = $this->request->get['filter_order_status_id'];
            } else {
                $filter_order_status_id = null;
            }

            $data = array(
                'filter_date_added_on'      => $filter_date_added_on,
                'filter_date_added_from'    => $filter_date_added_from,
                'filter_date_added_to'      => $filter_date_added_to,
                'filter_date_modified_on'   => $filter_date_modified_on,
                'filter_date_modified_from' => $filter_date_modified_from,
                'filter_date_modified_to'   => $filter_date_modified_to,
                'filter_order_status_id'    => $filter_order_status_id,
                'start'						=> ($page - 1) * $limit,
                'limit'						=> $limit
            );


            $results = $this->model_account_order->getOrdersByFilter($data);
            /*get all orders*/
            //$results = $this->model_account_order->getAllOrders($offset, $limit);

            $orders = array();

            if(count($results)){

                foreach ($results as $result) {

                    $orderData = $this->getOrderDetailsToOrder($result);

                    if (!empty($orderData)) {
                        $orders[] = $orderData;
                    }
                }

                if(count($orders) == 0){
                    $json['success'] 	= false;
                    $json['error'] 		= "No orders found";
                }else {
                    $json['data'] 	= $orders;
                }

            }else {
                $json['error'] 		= "No orders found";
                $json['success'] 	= false;
            }
        }else{
            $json['success'] 	= false;
        }

        $this->sendResponse($json);
    }

    /*Get order details*/
    public function getOrder($order_id) {

        $this->load->model('checkout/order');
        $this->load->model('account/order');

        $json = array('success' => true);

        if (ctype_digit($order_id)) {
            $order_info = $this->model_checkout_order->getOrder($order_id);

            if (!empty($order_info)) {
                $json['success'] 	= true;
                $json['data'] 		= $this->getOrderDetailsToOrder($order_info);

            } else {
                $json['success']     = false;
                $json['error']       = "The specified order does not exist.";

            }
        } else {
            $json['success']     = false;
            $json['error']       = "Invalid order id";

        }

        $this->sendResponse($json);
    }

    /*Get all orders of user */
    public function userorders(){

        $this->checkPlugin();

        $this->returnDeprecated();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){

            $json = array('success' => true);

            $user = null;

            /*check user parameter*/
            if (isset($this->request->get['user']) && $this->request->get['user'] != "" && ctype_digit($this->request->get['user'])) {
                $user = $this->request->get['user'];
            } else {
                $json['success'] 	= false;
            }

            if($json['success'] == true){
                $orderData['orders'] = array();

                $this->load->model('account/order');

                /*get all orders of user*/
                $results = $this->model_account_order->getOrdersByUser($user);

                $orders = array();

                foreach ($results as $result) {

                    $product_total = $this->model_account_order->getTotalOrderProductsByOrderId($result['order_id']);
                    $voucher_total = $this->model_account_order->getTotalOrderVouchersByOrderId($result['order_id']);

                    $orders[] = array(
                        'order_id'		=> $result['order_id'],
                        'name'			=> $result['firstname'] . ' ' . $result['lastname'],
                        'status'		=> $result['status'],
                        'date_added'	=> $result['date_added'],
                        'products'		=> ($product_total + $voucher_total),
                        'total'			=> $result['total'],
                        'currency_code'	=> $result['currency_code'],
                        'currency_value'=> $result['currency_value'],
                    );
                }

                if(count($orders) == 0){
                    $json['success'] 	= false;
                    $json['error'] 		= "No orders found";
                }else {
                    $json['data'] 	= $orders;
                }
            }else{
                $json['success'] 	= false;
            }
        }

        $this->sendResponse($json);
    }
    private function getOrderDetailsToOrder($order_info) {

        $this->load->model('catalog/product');

        $orderData = array();

        if (!empty($order_info)) {
            foreach($order_info as $key=>$value){
                $orderData[$key] = $value;
            }

            $orderData['products'] = array();

            $products = $this->model_account_order->getOrderProducts($orderData['order_id']);

            foreach ($products as $product) {
                $option_data = array();

                $options = $this->model_account_order->getOrderOptionsMod($orderData['order_id'], $product['order_product_id']);

                foreach ($options as $option) {
                    if ($option['type'] != 'file') {
                        $option_data[] = array(
                            'name'  => $option['name'],
                            'value' => $option['value'],
                            'type'  => $option['type'],
			    'product_option_id'  => isset($option['product_option_id']) ? $option['product_option_id'] : "",
			    'product_option_value_id'  => isset($option['product_option_value_id']) ? $option['product_option_value_id'] : "",
                            'option_id' => isset($option['option_id']) ? $option['option_id'] : "",
                            'option_value_id'  => isset($option['option_value_id']) ? $option['option_value_id'] : ""
                        );
                    } else {
                        $option_data[] = array(
                            'name'  => $option['name'],
                            'value' => utf8_substr($option['value'], 0, utf8_strrpos($option['value'], '.')),
                            'type'  => $option['type']
                        );
                    }
                }

                $origProduct = $this->model_catalog_product->getProduct($product['product_id']);

                $orderData['products'][] = array(
                    'order_product_id' => $product['order_product_id'],
                    'product_id'       => $product['product_id'],
                    'name'    	 	   => $product['name'],
                    'model'    		   => $product['model'],
                    'sku'			   => (!empty($origProduct['sku']) ? $origProduct['sku'] : "") ,
                    'option'   		   => $option_data,
                    'quantity'		   => $product['quantity'],
                    'price'    		   => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
                    'total'    		   => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value'])
                );
            }
        }

        $orderData['histories'] = array();

        $histories = $this->model_account_order->getOrderHistoriesRest($orderData['order_id'],0,1000 );

        foreach ($histories as $result) {
            $orderData['histories'][] = array(
                'notify'     => $result['notify'] ? $this->language->get('text_yes') : $this->language->get('text_no'),
                'status'     => $result['status'],
                'comment'    => nl2br($result['comment']),
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
            );
        }

	// Voucher
	$orderData['vouchers'] = array();

	$vouchers = $this->model_account_order->getOrderVouchers($orderData['order_id']);

	foreach ($vouchers as $voucher) {
		$orderData['vouchers'][] = array(
			'description' => $voucher['description'],
			'amount'      => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value'])
		);
	}

	// Totals
	$orderData['totals'] = array();

	$totals = $this->model_account_order->getOrderTotals($orderData['order_id']);

	foreach ($totals as $total) {
		$orderData['totals'][] = array(
			'title' => $total['title'],
			'text'  => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
		);
	}

        return $orderData;
    }

    /*
    * CUSTOMER FUNCTIONS
    */
    public function customers() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get customer details
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getCustomer($this->request->get['id']);
            }else {
                //get customers list
                $this->listCustomers();
            }
        }
    }

    /*
    * Get customers list
    */
    private function listCustomers() {

        $json = array('success' => true);

        $this->load->model('account/customer');

        $results = $this->model_account_customer->getCustomersMod();

        $customers = array();

        foreach ($results as $customer) {
            $customers[] = $this->getCustomerInfo($customer);
        }

        if(count($customers) == 0){
            $json['success'] 	= false;
            $json['error'] 		= "No customers found";
        }else {
            $json['data'] 		= $customers;
        }

        $this->sendResponse($json);
    }

    /*
    * Get customer details
    */
    private function getCustomer($id) {

        $json = array('success' => true);

        $this->load->model('account/customer');

        if (ctype_digit($id)) {
            $customer = $this->model_account_customer->getCustomer($id);
            if(!empty($customer['customer_id'])){
                $json['data'] = $this->getCustomerInfo($customer);
            }else {
                $json['success']     = false;
                $json['error']       = "The specified customer does not exist.";
            }
        } else {
            $json['success'] 	= false;
        }

        $this->sendResponse($json);
    }

    private function getCustomerInfo($customer) {
        // Custom Fields
        $this->load->model('account/custom_field');

        $custom_fields = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));

        if(strpos(VERSION, '2.1.') === false){
            $account_custom_field = unserialize($customer['custom_field']);
        } else {
            $account_custom_field = json_decode($customer['custom_field'], true);
        }

        return array(
            'store_id'                => $customer['store_id'],
            'customer_id'             => $customer['customer_id'],
            'firstname'               => $customer['firstname'],
            'lastname'                => $customer['lastname'],
            'telephone'               => $customer['telephone'],
            'fax'                     => $customer['fax'],
            'email'                   => $customer['email'],
            'account_custom_field'    => $account_custom_field,
            'custom_fields'           => $custom_fields

        );
    }
    /*
    * REVIEW FUNCTIONS
    */
    public function reviews() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
            //add review
            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);

            if ( isset($requestjson['order_product_id']) && isset($this->request->get['id']) && ctype_digit($this->request->get['id'])  
                && !empty($requestjson)) {
                $this->addReview($this->request->get['id'], $requestjson);
            }else {
                $this->response->setOutput(json_encode(array('success' => false)));
            }
        }else{
		    $this->response->setOutput(json_encode(array('success' => false)));
	    }
        
    }

    /*add review*/
    public function addReview($id, $post) {
		
        $json['success']     = false;

        $this->load->language('product/product');
        $post['name']=$this->customer->getFullName();
       
        if ((utf8_strlen($post['text']) < 1) || (utf8_strlen($post['text']) > 1000)) {
            $json['error']['warning'] = $this->language->get('error_text');
        }

        if (empty($post['rating']) || $post['rating'] < 0 || $post['rating'] > 5) {
            $json['error']['warning'] = $this->language->get('error_rating');
        }

        if (empty($post['order_product_id']) ) {
            $json['error']['warning'] = $this->language->get('error_order_product_id');
        }

        if (empty($post['is_anony']) || $post['is_anony'] < 0 || $post['is_anony'] > 1) {
            $post['is_anony']=0;

        }

        if (!isset($json['error'])) {
            $this->load->model('catalog/review');
            $this->model_catalog_review->addReview($id, $post);
            $json['success'] = "true";
        }
	
        $this->sendResponse($json);
    }

    /*
    * LANGUAGE FUNCTIONS
    */
    public function languages() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get language details
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getLanguage($this->request->get['id']);
            }else {
                //get languages list
                $this->listLanguages();
            }
        }
    }

    /*
* ORDER STATUSES FUNCTIONS
*/
    public function order_statuses() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get order statuses list
            $this->listOrderStatuses();
        }
    }

    /*
    * Get order statuses list
    */
    private function listOrderStatuses() {

        $json = array('success' => true);

        $this->load->model('account/order');

        $statuses = $this->model_account_order->getOrderStatuses();

        if(count($statuses) == 0){
            $json['success'] 	= false;
            $json['error'] 		= "No order status found";
        }else {
            $json['data'] 		= $statuses;
        }

        $this->sendResponse($json);
    }

    /*
    * Get languages list
    */
    private function listLanguages() {

        $json = array('success' => true);

        $this->load->model('localisation/language');

        $languages = $this->model_localisation_language->getLanguages();

        if(count($languages) == 0){
            $json['success'] 	= false;
            $json['error'] 		= "No language found";
        }else {
            $json['data'] 		= $languages;
        }

        $this->sendResponse($json);
    }

    /*
    * Get language details
    */
    private function getLanguage($id) {

        $json = array('success' => true);

        $this->load->model('localisation/language');

        if (ctype_digit($id)) {
            $result = $this->model_localisation_language->getLanguage($id);
        } else {
            $json['success']     = false;
            $json['error']       = "Not valid id";
        }

        if(!empty($result)){
            $json['data'] = array(
                'language_id' => $result['language_id'],
                'name'        => $result['name'],
                'code'        => $result['code'],
                'locale'      => $result['locale'],
                'image'       => $result['image'],
                'directory'   => $result['directory'],
                'filename'    => $result['filename'],
                'sort_order'  => $result['sort_order'],
                'status'      => $result['status']
            );
        }else {
            $json['success']     = false;
            $json['error']       = "The specified language does not exist.";
        }

        $this->sendResponse($json);
    }

    /*
    * STORE FUNCTIONS
    */
    public function stores() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get store details
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getStore($this->request->get['id']);
            }else {
                //get stores list
                $this->listStores();
            }
        }
    }

    /*
    * Get stores list
    */
    private function listStores() {

        $json = array('success' => true);

        $this->load->model('catalog/product');

        $results = $this->model_catalog_product->getStores();

        $stores = array();

        foreach ($results as $result) {
            $stores[] = array(
                'store_id'	=> $result['store_id'],
                'name'      => $result['name']
            );
        }

        $default_store[] = array(
            'store_id'	=> 0,
            'name'      => $this->config->get('config_name')
        );

        $data = array_merge($default_store, $stores);

        if(count($data) == 0){
            $json['success'] 	= false;
            $json['error'] 		= "No store found";
        }else {
            $json['data'] 		= $data;
        }

        $this->sendResponse($json);
    }

    /*
    * Get store details
    */
    private function getStore($id) {

        $json = array('success' => true);

        $this->load->model('catalog/product');
        $result = array();

        if (ctype_digit($id)) {
            $result = $this->model_catalog_product->getStore($id);
        } else {
            $json['success'] 	= false;
        }
        if(count($result)){
            // Store
            $json['data']['store_id'] = $id; // Store id


            foreach($result as $setting){
                switch($setting['key']){
                    case 'config_name':
                        $json['data']['store_name'] = $setting['value']; // Store title
                        break;
                    case 'config_owner':
                        $json['data']['store_owner'] = $setting['value']; // Store owner
                        break;
                    case 'config_geocode':
                        $json['data']['store_geocode'] = $setting['value']; // Store geocode
                        break;
                    case 'config_address':
                        $json['data']['store_address'] = $setting['value']; // Store address
                        break;
                    case 'config_email':
                        $json['data']['store_email'] = $setting['value']; // Store email
                        break;
                    case 'config_telephone':
                        $json['data']['store_telephone'] = $setting['value']; // Store telephone
                        break;
                    case 'config_fax':
                        $json['data']['store_fax'] = $setting['value']; // Store fax
                        break;
                    case 'config_open':
                        $json['data']['store_open'] = $setting['value']; // Store open
                        break;
                    case 'config_comment':
                        $json['data']['store_comment'] = $setting['value']; // Store comment
                        break;
                    case 'config_language':
                        $json['data']['store_language'] = $setting['value']; // Store language
                        break;
                    case 'config_url':
                        $json['data']['store_url'] = $setting['value']; // Store url
                        break;
                    case 'config_image':
                        $json['data']['store_image'] = $setting['value']; // Store image
			$this->load->model('tool/image');
			if (!empty($setting['value']) && is_file(DIR_IMAGE . $setting['value'])) {
				$json['data']['thumb'] = $this->model_tool_image->resize($setting['value'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
			} else {
				$json['data']['thumb'] = $this->model_tool_image->resize('no_image.png', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
			}
                        break;
                }

            }

        }else {
            $json['success']     = false;
            $json['error']       = "The specified store does not exist.";
        }

        $this->sendResponse($json);
    }


    /*
    * COUNTRY FUNCTIONS
    */
    public function countries() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get country details
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getCountry($this->request->get['id']);
            }else {
                $this->listCountries();
            }
        }
    }

    /*
    * Get countries
    */
    private function listCountries() {

        $json = array('success' => true);

        $this->load->model('localisation/country');

        $results = $this->model_localisation_country->getCountries();

        $data = array();

        foreach ($results as $country) {
            $data[] = $this->getCountryInfo($country, false);
        }

        if(count($results) == 0){
            $json['success'] 	= false;
            $json['error'] 		= "No country found";
        }else {
            $json['data'] 		= $data;
        }

        $this->sendResponse($json);
    }

    /*
    * Get country details
    */
    public function getCountry($country_id) {

        $json = array('success' => true);

        $this->load->model('localisation/country');

        $country_info = $this->model_localisation_country->getCountry($country_id);

        if(!empty($country_info)){
            $json["data"] = $this->getCountryInfo($country_info);
        }else {
            $json['success']     = false;
            $json['error']       = "The specified country does not exist.";
        }

        $this->sendResponse($json);
    }

    private function getCountryInfo($country_info, $addZone = true) {
        $this->load->model('localisation/zone');
        $info = array(
            'country_id'        => $country_info['country_id'],
            'name'              => $country_info['name'],
            'iso_code_2'        => $country_info['iso_code_2'],
            'iso_code_3'        => $country_info['iso_code_3'],
            'address_format'    => $country_info['address_format'],
            'postcode_required' => $country_info['postcode_required'],
            'status'            => $country_info['status']
        );
        if($addZone){
            $info['zone'] = $this->model_localisation_zone->getZonesByCountryId($country_info['country_id']);
        }

        return $info;
    }

    /*
    * SESSION FUNCTIONS
    */
    public function session() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get session details
            $this->getSessionId();
        }
    }

    /*
    * Get current session id
    */
    public function getSessionId() {

        $json = array('success' => true);
        session_regenerate_id();
        $json['data'] = array('session' => session_id());
        $this->sendResponse($json);
    }

    /*
    * FEATURED PRODUCTS FUNCTIONS
    */
    public function featured() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get featured products
            $limit = 0;

            if (isset($this->request->get['limit']) && ctype_digit($this->request->get['limit']) && $this->request->get['limit'] > 0) {
                $limit = $this->request->get['limit'];
            }

            $this->getFeaturedProducts($limit);
        }
    }

       /*
    * Get featured products
    */
    public function getFeaturedProducts($limit) {

        $json = array('success' => true);

        $this->load->model('catalog/product');


        $this->load->model('tool/image');

        $featureds = $this->model_catalog_product->getModulesByCode('featured');
        $data = array();
        $index  = 0;

        if(count($featureds)){
            foreach($featureds as $featured){
                $data[$index]['module_id'] = $featured['module_id'];
                $data[$index]['name'] = $featured['name'];
                $data[$index]['code'] = $featured['code'];

                if(strpos(VERSION, '2.1.') === false){
                    $settings = unserialize($featured['setting']);
                } else {
                    $settings = json_decode($featured['setting'], true);
                }

                $products = $settings['product'];

                if($limit){
                    $products = array_slice($products, 0, (int)$limit);
                }

                $all = $this->model_catalog_product->getProductsByIds($products, $this->customer);

                foreach ($all as $product_info) {

                    if ($product_info) {
                        if ($product_info['image']) {
                            $image = $this->model_tool_image->resize($product_info['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                        } else {
                            $image = false;
                        }

                        if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                            $price = $this->currency->restFormat($this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                            $price_formated = $this->currency->format($this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                        } else {
                            $price = false;
                            $price_formated = false;
                        }

                        if ((float)$product_info['special']) {
                            $special = $this->currency->restFormat(($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax'))));
                            $special_formated = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
                        } else {
                            $special = false;
                            $special_formated = false;
                        }

                        if ($this->config->get('config_review_status')) {
                            $rating = $product_info['rating'];
                        } else {
                            $rating = false;
                        }

                        $data[$index]['products'][] = array(
                            'product_id' => $product_info['product_id'],
                            'thumb'   	 => $image,
                            'name'       => $product_info['name'],
                            'clearqty'    	 => $product_info['clearqty'],
                            'price'   	 => $price,
                            'price_formated'=> $price_formated,
                            'special' 	 => $special,
                            'special_formated' 	 => $special_formated,
                            'rating'     => $rating,
                            'special_start_date'	=> (!empty($product_info['special_start_date']) ? $product_info['special_start_date'] : "") ,
                            'special_end_date'	=> (!empty($product_info['special_end_date']) ? $product_info['special_end_date'] : "") ,

                        );
                    }
                }
                $index++;
            }
        }
        $json['data'] = $data;
        $this->sendResponse($json);
    }

    /*
    * GET UTC AND LOCAL TIME DIFFERENCE
        * returns offset in seconds
    */
    public function utc_offset() {

        $this->checkPlugin();

        $json = array('success' => false);

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            $serverTimeZone = date_default_timezone_get();
            $timezone = new DateTimeZone($serverTimeZone);
            $now = new DateTime("now", $timezone);
            $offset = $timezone->getOffset($now);

            $json['data'] = array('offset' => $offset);
            $json['success'] = true;
        }

        $this->sendResponse($json);
    }

	/*
	* ADD ORDER HISTORY
	*/	
	public function orderhistory() {

		$this->checkPlugin();

		if ( $_SERVER['REQUEST_METHOD'] === 'PUT' ){
			$requestjson = file_get_contents('php://input');
	
			$requestjson = json_decode($requestjson, true);           

			if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])
				&& !empty($requestjson)) {
				$this->addOrderHistory($this->request->get['id'], $requestjson);
			}else {
				$this->response->setOutput(json_encode(array('success' => false)));
			}	
		}
    	}

	private function addOrderHistory($id, $data) {
		
	    $json = array('success' => true);
              	
		$this->load->model('checkout/order');
	   
		$order_info = $this->model_checkout_order->getOrder($id);

		if ($order_info) {
			$this->model_checkout_order->addOrderHistory($id, $data['order_status_id'], $data['comment'], $data['notify']);
		} else {
			$json["success"] = false;		
			$json["error"] = "Order not found";
		}

		$this->response->setOutput(json_encode($json));
	}

    //date format validator
    private function validateDate($date, $format = 'Y-m-d H:i:s')
    {
        $d = DateTime::createFromFormat($format, $date);
        return $d && $d->format($format) == $date;
    }

    /*
    * BESTSELLERS FUNCTIONS
    */
    public function bestsellers() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            $this->getBestsellers($this->request);
        }
    }

    /*check database modification*/
    private function getBestsellers($request) {

       $this->load->model('catalog/product');

        $this->load->model('tool/image');

        $data['products'] = array();

        /*check limit parameter*/
        $limit = 10;
        if (isset($request->get['limit']) && ctype_digit($request->get['limit'])) {
            $limit = $request->get['limit'];
        }

        $results = $this->model_catalog_product->getBestSellerProducts($limit);

        if ($results) {
            foreach ($results as $result) {
                if ($result['image']) {
                    $image = $this->model_tool_image->resize($result['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                } else {
                    $image = $this->model_tool_image->resize('placeholder.png', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                }

                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $price = false;
                }

                if ((float)$result['special']) {
                    $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $special = false;
                }

                if ($this->config->get('config_tax')) {
                    $tax = $this->currency->format((float)$result['special'] ? $result['special'] : $result['price']);
                } else {
                    $tax = false;
                }

                if ($this->config->get('config_review_status')) {
                    $rating = $result['rating'];
                } else {
                    $rating = false;
                }

                $data['products'][] = array(
                    'product_id'  => $result['product_id'],
                    'thumb'       => $image,
                    'name'        => $result['name'],
                    'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get('config_product_description_length')) . '..',
                    'price'       => $price,
                    'special'     => $special,
                    'price_excluding_tax'=> $tax,
                    'rating'      => $rating,
                    'href'        => $this->url->link('product/product', 'product_id=' . $result['product_id']),
                );
            }
        }


        $json = array('success' => true,'data' => $data);

        $this->sendResponse($json);
    }

    /*
    * CATEGORY FILTER FUNCTIONS
    */
    public function filters() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){

            $categoryId = 0;

            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $categoryId = $this->request->get['id'];
            }
            $this->getFilters($categoryId);
        }
    }

    /*get category filters*/
    private function getFilters($category_id) {

        $data = array();

        $this->load->model('catalog/category');

        $category_info = $this->model_catalog_category->getCategory($category_id);

        if ($category_info) {
            $data = $this->getCategoryFilters($category_id);
            $json = array('success' => true,'data' => $data);
        } else {
            $json = array('success' => false,'error' => "Category does not exist");
        }

        $this->sendResponse($json);
    }

    private function getCategoryFilters($category_id){
        $this->load->language('module/filter');
        $this->load->model('catalog/product');

        $data['filter_groups'] = array();

        $filter_groups = $this->model_catalog_category->getCategoryFilters($category_id);

        if ($filter_groups) {
            foreach ($filter_groups as $filter_group) {
                $childen_data = array();

                foreach ($filter_group['filter'] as $filter) {
                    $filter_data = array(
                        'filter_category_id' => $category_id,
                        'filter_filter' => $filter['filter_id']
                    );

                    $childen_data[] = array(
                        'filter_id' => $filter['filter_id'],
                        'name' => $filter['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : '')
                    );
                }

                $data['filter_groups'][] = array(
                    'filter_group_id' => $filter_group['filter_group_id'],
                    'name' => $filter_group['name'],
                    'filter' => $childen_data
                );
            }
        }

        return $data;
    }

    /*
    * SLIDESHOW FUNCTIONS
    */
    public function slideshows() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            $this->getSlideshows();
        }
    }

    /*
     * Get slideshows
     */
    public function getSlideshows() {

        $json = array('success' => true);

        $this->load->model('catalog/product');
        $this->load->model('extension/module');
        $this->load->model('design/banner');
        $this->load->model('tool/image');

        $slideshows = $this->model_catalog_product->getModulesByCode('slideshow');
        $data = array();
        $index  = 0;

        if(count($slideshows)){
            foreach($slideshows as $slideshow){
                $module_info = $this->model_extension_module->getModule($slideshow['module_id']);
                $data[$index]['module_id'] = $slideshow['module_id'];
                $data[$index]['name'] = $module_info['name'];
                $data[$index]['banner_id'] = $module_info['banner_id'];
                $data[$index]['width'] = $module_info['width'];
                $data[$index]['height'] = $module_info['height'];
                $data[$index]['status'] = $module_info['status'];

                $data[$index]['banners'] = array();

                $results = $this->model_design_banner->getBanner($module_info['banner_id']);

                foreach ($results as $result) {
                    if (is_file(DIR_IMAGE . $result['image'])) {
                        $data[$index]['banners'][] = array(
                            'title' => $result['title'],
                            'link'  => $result['link'],
                            'image' => $this->model_tool_image->resize($result['image'], $module_info['width'], $module_info['height'])
                        );
                    }
                }
                $index++;
            }
        }
        $json['data'] = $data;
        $this->sendResponse($json);
    }
    /*
    * GET RELATED PRODUCT FUNCTIONS
    */
    public function related() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){

            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getRelated($this->request->get['id']);
            } else {
                $this->sendResponse(array('success' => false, 'Product id is required.'));
            }

        } else {
            $this->sendResponse(array('success' => false, 'error'=>'Invalid HTTP method'));
        }
    }
    /*get related json*/
     private function getRelatedjson($id) {
        $this->load->model('tool/image');
        $data = array();

        $this->load->model('catalog/product');

        $results = $this->model_catalog_product->getProductRelated($id);
        $data['products'] = array();
        foreach ($results as $result) {
            if ($result['image']) {
                $image = $this->model_tool_image->resize($result['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
            } else {
                $image = $this->model_tool_image->resize('placeholder.png', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
            }

            if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
            } else {
                $price = false;
            }

            if ((float)$result['special']) {
                $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
            } else {
                $special = false;
            }

            if ($this->config->get('config_tax')) {
                $tax = $this->currency->format((float)$result['special'] ? $result['special'] : $result['price']);
            } else {
                $tax = false;
            }

            if ($this->config->get('config_review_status')) {
                $rating = (int)$result['rating'];
            } else {
                $rating = false;
            }

            $data['products'][] = array(
                'product_id'  => $result['product_id'],
                'thumb'       => $image,
                'name'        => $result['name'],
                'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get('config_product_description_length')) . '..',
                'price'       => $price,
                'special'     => $special,
                'price_excluding_tax'=> $tax,
                'minimum'     => $result['minimum'] > 0 ? $result['minimum'] : 1,
                'rating'      => $rating,
            );
        }

        if (!empty($data['products'])) {
            $json = array('success' => true,'data' => $data['products']);
        } else {
            $json = array('success' => false,'error' => "No related product found");
        }

        return $json;
    }


    /*get related products*/
    private function getRelated($id) {
        $this->load->model('tool/image');
        $data = array();

        $this->load->model('catalog/product');

        $results = $this->model_catalog_product->getProductRelated($id);
        $data['products'] = array();
        foreach ($results as $result) {
            if ($result['image']) {
                $image = $this->model_tool_image->resize($result['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
            } else {
                $image = $this->model_tool_image->resize('placeholder.png', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
            }

            if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
            } else {
                $price = false;
            }

            if ((float)$result['special']) {
                $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
            } else {
                $special = false;
            }

            if ($this->config->get('config_tax')) {
                $tax = $this->currency->format((float)$result['special'] ? $result['special'] : $result['price']);
            } else {
                $tax = false;
            }

            if ($this->config->get('config_review_status')) {
                $rating = (int)$result['rating'];
            } else {
                $rating = false;
            }

            $data['products'][] = array(
                'product_id'  => $result['product_id'],
                'thumb'       => $image,
                'name'        => $result['name'],
                'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get('config_product_description_length')) . '..',
                'price'       => $price,
                'special'     => $special,
                'price_excluding_tax'=> $tax,
                'minimum'     => $result['minimum'] > 0 ? $result['minimum'] : 1,
                'rating'      => $rating,
            );
        }

        if (!empty($data['products'])) {
            $json = array('success' => true,'data' => $data['products']);
        } else {
            $json = array('success' => false,'error' => "No related product found");
        }

        $this->sendResponse($json);
    }

    /*
    * GET LATEST PRODUCT FUNCTIONS
    */
    public function latest() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            $limit = 10;
            if (isset($this->request->get['limit']) && ctype_digit($this->request->get['limit'])) {
                $limit = $this->request->get['limit'];
            }
            $this->getLatest($limit);
        } else {
            $this->sendResponse(array('success' => false, 'error'=>'Invalid HTTP method'));
        }
    }

    /*get latest products*/
    private function getLatest($limit) {

        $data = array();

        $this->load->model('catalog/product');

        $this->load->model('tool/image');

        $data['products'] = array();

        $filter_data = array(
            'sort'  => 'p.date_added',
            'order' => 'DESC',
            'start' => 0,
            'limit' => $limit
        );

        $results = $this->model_catalog_product->getProducts($filter_data);

        if ($results) {
            foreach ($results as $result) {
                if ($result['image']) {
                    $image = $this->model_tool_image->resize($result['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                } else {
                    $image = $this->model_tool_image->resize('placeholder.png', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                }

                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $price = false;
                }

                if ((float)$result['special']) {
                    $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $special = false;
                }

                if ($this->config->get('config_tax')) {
                    $tax = $this->currency->format((float)$result['special'] ? $result['special'] : $result['price']);
                } else {
                    $tax = false;
                }

                if ($this->config->get('config_review_status')) {
                    $rating = $result['rating'];
                } else {
                    $rating = false;
                }

                $data['products'][] = array(
                    'product_id'  => $result['product_id'],
                    'thumb'       => $image,
                    'name'        => $result['name'],
                    'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get('config_product_description_length')) . '..',
                    'price'       => $price,
                    'special'     => $special,
                    'price_excluding_tax'=> $tax,
                    'rating'      => $rating
                );
            }
        }

        if (!empty($data['products'])) {
            $json = array('success' => true,'data' => $data['products']);
        } else {
            $json = array('success' => false,'error' => "No latest product found");
        }

        $this->sendResponse($json);
    }

    /*
    * INFORMATIONS FUNCTIONS
    */
    public function information() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get information details
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getInformation($this->request->get['id']);
            }else {
                //get information list
                $this->listInformation();
            }
        }
    }

    /*
    * Get information list
    */
    public function listInformation() {
        $this->load->language('module/information');

        $this->load->model('catalog/information');

        $informations = array();

        foreach ($this->model_catalog_information->getInformations() as $result) {
            $informations[] = array(
                'id'=>$result['information_id'],
                'title' => $result['title']
            );
        }

        if(empty($informations)){
            $json['success'] 	= false;
            $json['error'] 	= "No information found";
        }else {
            $json['data'] 	= $informations;
        }

        $this->sendResponse($json);
    }

    /*
    * Get information details
    */
    public function getInformation($id) {

        $json = array('success' => true);

        $this->load->language('information/information');
        $this->load->model('catalog/information');

        if (ctype_digit($id)) {
            $information_info = $this->model_catalog_information->getInformation($id);
            if($information_info){
                $json['data'] = $information_info;
            } else {
                $json['success']     = false;
                $json['error']       = "The specified information does not exist.";
            }
        } else {
            $json['success'] 	= false;
        }

        $this->sendResponse($json);
    }

    /*
    * BANNER FUNCTIONS
    */
    public function banners() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            //get banner details
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->getBanner($this->request->get['id']);
            }else {
                //get banner list
                $this->listBanners();
            }
        }
    }

    /*
    * Get banner list
    */
    public function listBanners() {
        $this->load->language('module/banner');
        $this->load->model('catalog/product');

        $banners = $this->model_catalog_product->getBanners();

        if(empty($banners)){
            $json['success'] 	= false;
            $json['error'] 	= "No banner found";
        }else {
            $json['data'] 	= $banners;
        }

        $this->sendResponse($json);
    }

    /*
    * Get banner details
    */
    public function getBanner($id) {

        $json = array('success' => true);

        $this->load->model('design/banner');
        $this->load->model('tool/image');
        $this->load->model('setting/setting');

        if (ctype_digit($id)) {
            $banners = array();

            $results = $this->model_design_banner->getBanner($id);

            foreach ($results as $result) {
                if (is_file(DIR_IMAGE . $result['image'])) {
                    $banners[] = array(
                        'title' => $result['title'],
                        'link'  => $result['link'],
                        'image' => $this->model_tool_image->resize($result['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'))
                    );
                }
            }
            if(!empty($banners)){
                $json['data'] = $banners;
            } else {
                $json['success']     = false;
                $json['error']       = "The specified banner does not exist.";
            }
        } else {
            $json['success'] 	= false;
        }

        $this->sendResponse($json);
    }
    /*
    * GET SPECIAL PRODUCT FUNCTIONS
    */
    public function specials() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            $limit = 10;
            if (isset($this->request->get['limit']) && ctype_digit($this->request->get['limit'])) {
                $limit = $this->request->get['limit'];
            }
            $this->getSpecials($limit);
        } else {
            $this->sendResponse(array('success' => false, 'error'=>'Invalid HTTP method'));
        }
    }

    /*get special products*/
    private function getSpecials($limit) {

        $data = array();

        $this->load->model('catalog/product');

        $this->load->model('tool/image');

        $data['products'] = array();

        $filter_data = array(
            'sort'  => 'pd.name',
            'order' => 'ASC',
            'start' => 0,
            'limit' => $limit
        );


        $results = $this->model_catalog_product->getProductSpecials($filter_data);

        if ($results) {
            foreach ($results as $result) {
                if ($result['image']) {
                    $image = $this->model_tool_image->resize($result['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                } else {
                    $image = $this->model_tool_image->resize('placeholder.png', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                }

                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $price = false;
                }

                if ((float)$result['special']) {
                    $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $special = false;
                }

                if ($this->config->get('config_tax')) {
                    $tax = $this->currency->format((float)$result['special'] ? $result['special'] : $result['price']);
                } else {
                    $tax = false;
                }

                if ($this->config->get('config_review_status')) {
                    $rating = $result['rating'];
                } else {
                    $rating = false;
                }

                $data['products'][] = array(
                    'product_id'  => $result['product_id'],
                    'thumb'       => $image,
                    'name'        => $result['name'],
                    'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get('config_product_description_length')) . '..',
                    'price'       => $price,
                    'special'     => $special,
                    'tax' => $tax,
                    'rating'      => $rating,
                    'href'        => $this->url->link('product/product', 'product_id=' . $result['product_id'])
                );
            }
        }

        if (!empty($data['products'])) {
            $json = array('success' => true,'data' => $data['products']);
        } else {
            $json = array('success' => false,'error' => array('warning'=> "没有找到此产品"));
        }

        $this->sendResponse($json);
    }




    public function homepage() {
        if ($this->session->data['is_he']!=1) {
            $this->checkPlugin();
            
        }else{
            $url = $this->url->link('common/index', '', 'SSL') . '#/luckydraw/8';

        }
        $cache = new Cache('file', 120);
        $home_page_info = $cache->get('home_page_info');
        $columnname  = array(
                    '0' => "product",
                    '1' => "vendor",
                    '2' => "category",
                    );
        if($home_page_info) {
            $this->sendResponse($home_page_info);
        }else{
            $this->load->model('catalog/product');
            $this->load->model('extension/module');
            $this->load->model('design/banner');
            $this->load->model('tool/image');
            $this->load->model('catalog/category');
          
            if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
                $json = array();
                //获取slider，此处hardcode slider的名称为首页APP
                $module_info = $this->model_extension_module->getModuleByName('首页APP');
                $data['name'] = $module_info['name'];
                $data['banner_id'] = $module_info['banner_id'];
                $data['width'] = $module_info['width'];
                $data['height'] = $module_info['height'];
                $data['status'] = $module_info['status'];
                $data['banners'] = array();
                $results = $this->model_design_banner->getBanner($module_info['banner_id']);
                
                foreach ($results as $key => $result) {
                    if (is_file(DIR_IMAGE . $result['image'])) {
                        if(in_array(trim($result['title']),$columnname)){   
                            $data['banners'][] = array(
                                'title' => $result['title'],
                                'link'  => $result['link'],
                                $result['title']."_id" => $result['link'],
                                'image' => $this->model_tool_image->resize($result['image'], 375*2, 182*2),
                            );
                        } else {
                            $data['banners'][] = array(
                                'title' => $result['title'],
                                'link'  => $result['link'],
                                // 'image' => $this->model_tool_image->resize($result['image'], $module_info['width'], $module_info['height'])
                                'image' => $this->model_tool_image->resize($result['image'], 375*2, 182*2),
                            );    
                        }
                        
                        
                    }
                }
                $json['slider'] = $data;
                //获取两个banner
                $data = array();
                $results = $this->model_design_banner->getBannerByName("首页广告1");
                
                foreach ($results as $key => $result) {
                    if (is_file(DIR_IMAGE . $result['image'])) {


                        $banners[$key] = array(
                            'title' => $result['title'],
                            'link'  => $result['link'],
                            'image' => $this->model_tool_image->resize($result['image'], 370*2, 89*2)
                        );
                        if(in_array(trim($result['title']),$columnname)){
                            $banners[$key][$result['title']."_id"] = $result['link'];     
                        }

                    }
                }
                if(!empty($banners)){
                    $data = $banners;
                } else {
                    $json['success']     = false;
                    $json['error']['warning']       = "The specified banner does not exist.";
                }
                $json['banner_1'] = $data;

                $data = array();
                $banners = array();
                $results = $this->model_design_banner->getBannerByName("首页广告2");

                foreach ($results as $key => $result) {
                    if (is_file(DIR_IMAGE . $result['image'])) {
                        $banners[$key] = array(
                            'title' => $result['title'],
                            'link'  => $result['link'],
                            // 'image' => $this->model_tool_image->resize($result['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'))
                            'image' => $this->model_tool_image->resize($result['image'], 370*2, 89*2)
                        );
                        if(in_array(trim($result['title']),$columnname)){
                            $banners[$key][$result['title']."_id"] = $result['link'];     
                        }
                    }
                }
                if(!empty($banners)){
                    $data = $banners;
                } else {
                    $json['success']     = false;
                    $json['error']['warning']       = "The specified banner does not exist.";
                }
                $json['banner_2'] = $data;

                //获取最新到货
                $category = $this->model_catalog_category->getCategoryByName('最新到货');
                if(isset($category['category_id'])){
                    if (isset($category['image']) && file_exists(DIR_IMAGE . $category['image'])) {
                        $image = $this->model_tool_image->resize($category['image'], 183*2, 116*2);
                    } else {
                        $image = $this->model_tool_image->resize('no_image.jpg', 183*2, 116*2);
                    }
                    $info = array(
                        'id'            => $category['category_id'],
                        'name'          => $category['name'],
                        'description'   => $category['description'],
                        'image'         => $image,
                        'link'          => 'feed/rest_api/categories&id=' . $category['category_id'],
                        'category_id'   => $category['category_id'],
                    );
                }
                $json['new_arrival'] = $info; 

                //获取编辑推荐
                $category = $this->model_catalog_category->getCategoryByName('编辑推荐');
                if(isset($category['category_id'])){
                    if (isset($category['image']) && file_exists(DIR_IMAGE . $category['image'])) {
                        $image = $this->model_tool_image->resize($category['image'], 183*2, 116*2);
                    } else {
                        $image = $this->model_tool_image->resize('no_image.jpg', 183*2, 116*2);
                    }
                    $info = array(
                        'id'            => $category['category_id'],
                        'name'          => $category['name'],
                        'description'   => $category['description'],
                        'image'         => $image,
                        'link'          => 'feed/rest_api/categories&id=' . $category['category_id'],
                        'category_id'   => $category['category_id'],
                    );
                }
                $json['special'] = $info;        

                //获取四个制造商
                 $data = array("sort"=>'sort_order',"order"=>'DESC',"limit"=>4);
                 $manu_info=$this->homepagelistVendors($data);   

                 $json['vendor'] = $manu_info;   

                //获取七个一级分类
                 $cate_info = $this->getToplevelCatsForHomepage();
                 $json['categories'] = $cate_info; 

                $json['products'] = array(); 

                $cache->set('home_page_info',$json);
                $this->sendResponse($json);
            }
        }

    }

    public function getSignPackage(){
        $opt = array(
            'appsecret'=>WxPayConfig::APPSECRET,
            'appid'=>WxPayConfig::APPID,
            'cachedir'=>DIR_CACHE
        );
        
        $we = new EasyWechat($opt);
        $auth = $we->checkAuth();
        $js_ticket = $we->getJsTicket();
        if (!$js_ticket) {
            echo "获取js_ticket失败！<br>";
            echo '错误码：'.$we->errCode;
            exit;
        }
        $url = $this->request->get['url'];
        $js_sign = $we->getJsSign($url);
        $this->sendResponse($js_sign);  
    }

    public function getLogcentership(){
        $this->load->model('catalog/product');
        $logcenter_id = $this->customer->getLogcenterId();
        $data = array();
        $data['logcenter_zone_name'] =  $this->model_catalog_product->getLogcenterInfoByLogcenterId($logcenter_id);
        $data['time'] = '2';
        $data['text'] = !empty($data['logcenter_zone_name'])?'从'.$data['logcenter_zone_name'].' 物流中心 发货预计'.$data['time'].'天到达':'无';
        return $data;
    }
    public function getNumCategory($name = '',$num = 1,$flag = 0){
        $this->load->model('catalog/category');
        for ($i=0; $i < $num; $i++) { 
            $n = $i+1;
            $category = null;
            $info = null;
            $category = $this->model_catalog_category->getCategoryByName($name.($flag?$n:''));
            if(isset($category['category_id'])){
                if (isset($category['home_image']) && file_exists(DIR_IMAGE . $category['home_image'])) {
                    $image = $this->model_tool_image->resize($category['home_image'], 475, 304);
                    } else {
                        $image = $this->model_tool_image->resize('no_image.jpg', 475, 304);
                    }
                    $info = array(
                        'id'            => $category['category_id'],
                        'name'          => $category['meta_title'],
                        'description'   => $category['description'],
                        'image'         => $image,
                        // 'link'          => 'feed/rest_api/categories&id=' . $category['category_id'],
                        // 'category_id'   => $category['category_id'],
                    );
                    }
                $data[$i] = $info;
            }
        return $data;
    }

    public function getSelectProductByCategory($category_id){
        $this->load->model('catalog/product');
        $data['filter_category_id'] = $category_id; 
        $data['sort'] = "p.sort_order";
        $data['order'] = "DESC";
        $data['limit'] = 12;
        $query = $this->model_catalog_product->getProducts($data);
        return $query;
    }

    public function pc_homepage(){
        $this->checkPlugin();
        $cache = new Cache('file', 120);
        //$cache->delete('pc_home_page_info');
        $pc_home_page_info = $cache->get('pc_home_page_info');
        $data = array();
        if($pc_home_page_info) {          
            $this->sendResponse($pc_home_page_info);
        }else{
            
            $this->load->model('catalog/product');
            $this->load->model('extension/module');
            $this->load->model('design/banner');
            $this->load->model('tool/image');
            $this->load->model('catalog/category');
            $this->load->model('catalog/vendor');

            if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
                $json = array();
                $category = $this->loadCatTree(0,2);
                $json['category'] = $category;
                $module_info = $this->model_extension_module->getModuleByName('PC首页');
                $data['name'] = $module_info['name'];
                $data['banner_id'] = $module_info['banner_id'];
                $data['width'] = $module_info['width'];
                $data['height'] = $module_info['height'];
                $data['status'] = $module_info['status'];
                $data['banners'] = array();


                $results = $this->model_design_banner->getBannerByName("PC首页轮播");
                $banners  = array();
                foreach ($results as $key => $result) {
                    if (is_file(DIR_IMAGE . $result['image'])) {
                        $banners[$key] = array(
                            'title' => $result['title'],
                            'link'  => $result['link'],
                            'image' => $this->model_tool_image->resize($result['image'], 990, 400)
                        );
                        if(in_array(trim($result['title']),$columnname)){
                            $banners[$key][$result['title']."_id"] = $result['link'];     
                        }

                    }
                    
                }

                $json['banners'] = $banners;

                $results1 = $this->model_design_banner->getBannerByName("PC中间图片");
                $banners1  = array();
                foreach ($results1 as $key => $result) {
                    if (is_file(DIR_IMAGE . $result['image'])) {
                        $banners1[$key] = array(
                            'title' => $result['title'],
                            'link'  => $result['link'],
                            'image' => HTTP_SERVER.'image/'.$result['image'],
                        );
                        if(in_array(trim($result['title']),$columnname)){
                            $banners1[$key][$result['title']."_id"] = $result['link'];     
                        }

                    }
                    
                }
                $json['banners_center'] = $banners1;

                $results2 = $this->model_design_banner->getBannerByName("PC顶部图片");
                $banners2  = array();
                foreach ($results2 as $key2 => $result2) {
                    if (is_file(DIR_IMAGE . $result2['image'])) {
                        $banners2[$key] = array(
                            'title' => $result2['title'],
                            'link'  => $result2['link'],
                            'image' => HTTP_SERVER.'image/'.$result2['image'],
                        );
                        if(in_array(trim($result2['title']),$columnname)){
                            $banners2[$key][$result['title']."_id"] = $result2['link'];     
                        }

                    }
                    
                }
                $json['banners_top'] = $banners2;

                $json['boommain'] = $this->getNumCategory("爆款专区")['0'];
                $json['boom'] = $this->getNumCategory("爆款专区",4,1);

                // $data = array("sort"=>'sort_order',"order"=>'DESC',"limit"=>8);
                // $manu_info=$this->homepagelistVendors($data);  
                // $json['vendor'] = $manu_info;

                $json['recommendmain'] = $this->getNumCategory("精选推荐")['0'];
                $json['recommend'] = $this->getNumCategory("精选推荐",6,1);

                $json['hotmain'] = $this->getNumCategory("火热新品")['0'];
                $json['hot'] = $this->getNumCategory("火热新品",6,1);
                

                foreach ($category as $key1 => $result1) {
                    //Liqn 暂时性隐藏没有商品的分类 @ 2016-04-28
                    // if(in_array($result1['name'], array('餐具', '砧板筷子', '清洁/卫浴'))) {
                    //     continue;
                    // }

                    $products[$key1]['name'] =  $result1['name'];
                    $products[$key1]['category_id'] = $result1['category_id'];
					$products[$key1]['class_sort'] = $result1['class_sort'];
                    $i=0;
                    foreach ($result1['categories'] as $key2 => $value2) {

                                $products[$key1]['categories'][$i]['name'] = $value2['name'];
                                $products[$key1]['categories'][$i]['category_id'] = $value2['category_id'];
                                $i++;
                             }  
                    $productsinfo = $this->getSelectProductByCategory($result1['category_id']);
                    $data2 =null;
                    foreach ($productsinfo as $key => $value) {
                        $data2[] = $this->getProductInfo($value);
                        foreach ($data2 as $id => $tmp) {
                            $data2[$id]['product_id'] = $data2[$id]['id'];
                        }
                        // $data2[] = array(
                        //     'name' => $value['name'],
                        //     'product_id' => $value['product_id'],
                        //     'image'      => $this->model_tool_image->resize($value['image'], 400, 400),
                        //     );
                    }
                    $products[$key1]['products'] = $data2;    
                }
                $json['products'] = $products;

                $vendors = $this->model_catalog_vendor->getTopVendor(6,3);
                foreach ($vendors as $vendors_key1 => $vendors_value1) {
                    $vendors_data[$vendors_key1]['vendor_name'] = $vendors_value1['vendor_name'];
                    $vendors_data[$vendors_key1]['vendor_id']  = $vendors_value1['vendor_id'];
                    $vendors_data[$vendors_key1]['vendor_image']  = $this->model_tool_image->resize($vendors_value1['vendor_image'],473,326);
                    $i =0;
                    foreach ($vendors_value1['products'] as $vendors_key2 => $vendors_value2) {
                        $vendors_data2 = array(
                            'product_id' => $vendors_value2['product_id'],
                            'product_name'=> $vendors_value2['name'],
                            'jan'=> $vendors_value2['jan'],
                            'upc'=> $vendors_value2['upc'],
                            'image'       => $this->model_tool_image->resize($vendors_value2['image'], 400, 400),
                             );
                        $vendors_data[$vendors_key1]['products'][$i] = $vendors_data2;
                        $i++;
                    }

                }
                $json['vendors'] = $vendors_data;
                $this->sendResponse($json);
                $cache->set('pc_home_page_info',$json);
            }   
        }   
    }

    public function upload() {
        $this->load->language('tool/upload');
        $json = array();
        if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
            // Sanitize the filename
            $filename = basename(preg_replace('/[^a-zA-Z0-9\.\-\s+]/', '', html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8')));

            // Validate the filename length
            if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 64)) {
                $json['error'] = $this->language->get('error_filename');
            }

            // Allowed file extension types
            $allowed = array();

            $extension_allowed = preg_replace('~\r?\n~', "\n", $this->config->get('config_file_ext_allowed'));

            $filetypes = explode("\n", $extension_allowed);

            foreach ($filetypes as $filetype) {
                $allowed[] = trim($filetype);
            }

            if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
                $json['error'] = $this->language->get('error_filetype');
            }

            // Allowed file mime types
            $allowed = array();

            $mime_allowed = preg_replace('~\r?\n~', "\n", $this->config->get('config_file_mime_allowed'));

            $filetypes = explode("\n", $mime_allowed);

            foreach ($filetypes as $filetype) {
                $allowed[] = trim($filetype);
            }

            if (!in_array($this->request->files['file']['type'], $allowed)) {
                $json['error'] = $this->language->get('error_filetype');
            }

            // Check to see if any PHP files are trying to be uploaded
            $content = file_get_contents($this->request->files['file']['tmp_name']);

            if (preg_match('/\<\?php/i', $content)) {
                $json['error'] = $this->language->get('error_filetype');
            }

            // Return any upload error
            if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
                $json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
            }
        } else {
            $json['error'] = $this->language->get('error_upload');
        }

        if (!$json) {
            $file = $filename . '.' . md5(mt_rand());

            move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD . $file);

            // Hide the uploaded file name so people can not link to it directly.
            $this->load->model('tool/upload');

            $json['code'] = $this->model_tool_upload->addUpload($filename, $file);
            //返回img url给前端
            $base_url = $this->config->get('config_url');
            $img_url = $base_url . 'system/storage/upload/' . $file;
            $json['img_url'] = $img_url;

            $json['success'] = $this->language->get('text_upload');
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function wxupload() {
      // $this->checkPlugin();
      $this->load->language('tool/upload');
      $json = array('success'=>false);
      if (!$this->customer->isLogged()) {
        $json["error"]["warning"] = "用户还没有登陆";
        $this->response->setOutput(json_encode($json));
        return;
      }
      
      // $media_id = $this->request->post['media_id'];
      $requestjson = file_get_contents('php://input');
      $requestjson = json_decode($requestjson, true);   
      $media_id = $requestjson['media_id'];

      $opt = array(
            'appsecret'=>WxPayConfig::APPSECRET,
            'appid'=>WxPayConfig::APPID,
            'cachedir'=>DIR_CACHE
      );
      $jssdk = new EasyWechat($opt);
      $file_content = $jssdk->getMedia($media_id);
      if(!$file_content){
        $json["error"]["warning"] = $jssdk->errMsg;
        $this->response->setOutput(json_encode($json));
        return;
      }

      $file_name = $media_id . '.jpg';
      $file_path = DIR_UPLOAD . $file_name;

      file_put_contents($file_path, $file_content);

      //保存到统一的upload数据表
      $this->load->model('tool/upload');
      $code = $this->model_tool_upload->addUpload($file_name, $file_name);
      $json['code'] = $code;
      //返回img url给前端
      $base_url = $this->config->get('config_url');
      $img_url = $base_url . 'system/storage/upload/' . $file_name;
      $json['img_url'] = $img_url;

      $json['success'] = $this->language->get('text_upload');

      $this->response->addHeader('Content-Type: application/json');
      $this->response->setOutput(json_encode($json));
    }

    public function autoConfirmShipment(){
        $this->load->model('checkout/order');
        $status = $this->model_checkout_order->findOrderStatus('全部发货');
        $ordersdata = $this->model_checkout_order->getOrdersByOederStatusId($status);
        $result = $this->saveOrdersStatus($ordersdata,'完成','48小时之后系统自动确认收货');
    }

    public function confirmShipment(){
        $order_id = I('get.order_id');
        $json['success'] = true;
        if(empty($order_id)){
            $json['success'] = false;
            $json["error"]["warning"] = "订单号不对";
        } 

        if($json['success']){
            $order_product_status = $this ->getProductsStatusByOrderId($order_id);
            if(!$order_product_status){
                $json['success'] = false;
                $json['error']['warning'] = '订单中仍有货物未发送';
            }
        }

        if($json['success']){
            $order_status = $this ->checkOrderStatusIdByOrderId($order_id);
            if($order_status){
                $this->saveOrderStatus($order_id,'完成','用户确认收货'); 
            }else{
                $json['success'] = false;
                $json['error']['warning'] = '修改订单失败';
            }
        }

        $this->sendResponse($json);

    }

    private function getProductsStatusByOrderId($order_id){
        $this->load->model('catalog/product');
        $result = $this->model_catalog_product->getProductsStatusByOrderId($order_id);
        return $result;
    } 

    private function saveOrderStatus($order_id,$status,$content){

        $this->load->model('checkout/order');
        $status = $this->model_checkout_order->findOrderStatus($status);
        $result = $this->model_checkout_order->addOrderHistory($order_id,$status,$content);
        return $result;
    } 

    private function checkOrderStatusIdByOrderId($order_id){
        $this->load->model('checkout/order');
        $result = $this->model_checkout_order->checkOrderStatusIdByOrderId($order_id);
        return $result;
    }

    private function saveOrdersStatus($order_id,$status,$content){

        foreach ($order_id as $key) {
            $result = $this->saveOrderStatus($key['order_id'],$status,$content);
        }
    }

	public function test(){
		
		$keyword = '测试';

		/*全文搜索*/
		require_once(DIR_SYSTEM . 'xunsearch/php/lib/XS.php');

		$xs = new XS('bhz');

		$search = $xs->search;   //获取搜索对象
		
		$search->setFuzzy(true);	 //模糊搜索
		$search->setLimit($limit,$start);

		$products = $search->setAutoSynonyms()->setQuery($keyword)->search();  //搜索
		/*全文搜索*/
		
		$pdata = array();
		foreach($products as $v){			
			if($v->status == 1){
				$pdata[] = array(
					'name' => $v->name,
					'product_id' => $v->product_id
				);
			}
		}

		$count;
        if(count($pdata) == 0 || empty($pdata)){
            $json['success'] = true;
            $json['data'] = array();
			$count = count($pdata);
        }
		else{
            $json['success'] = true;
            foreach ($pdata as $data) {
				$temp = $this->getListInfo($data);
				if($temp){
					$json['data'][] = $temp;
				}
            }
			$count = count($json['data']);
			if($count == 0){
				$json['data'] = array();
			}
        }

		print_r($json);

	}

    public function sendcoupon(){
        $post = array();
        
        if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){

            $requestjson = file_get_contents('php://input');
            
            $requestjson = json_decode($requestjson, true);
            $this->load->model('catalog/product');
            $this->model_catalog_product->sendcoupon($requestjson);
            // var_dump($requestjson);

        }
        $json['is_receive'] = 1;
        $this->sendResponse($json);

    }

}
